Setting a control's ID in code behind for use in a validation control

1.1k views Asked by At

How can I use validation controls within server controls? The issue that I have is that by default if I do something like this:

private TextBox _textbox;
RequiredFieldValidator _validator;

protected override void OnInit(object sender, EventArgs e)
{
    _textbox= new TextBox {ID = "test"};
    _validator = new RequiredFieldValidator{ControlToValidate = _textbox.ID};
}

protected override void OnLoad(object sender, EventArgs e)
{
    this.Controls.Add(_textbox);
    this.Controls.Add(_validator);
}

Then it works fine but because I've set the ID in code behind the textbox has an ID of test in the actual generated HTML (instead of ctl1_ctl2_test or or something.) This means that if I use the control twice on the same page then I get an error. If I don't set an ID then it is null and the validator can't find the control.

Any help would be great,

Thanks,

Joe

1

There are 1 answers

0
Michael Liu On BEST ANSWER

Just add INamingContainer to the list of interfaces implemented by your server control:

public class RequiredTextBox : Control, INamingContainer

Now the ID of the child TextBox will be scoped by the ID of the server control, thus avoiding ID conflicts.