Hi,
I have been researching how to create a control that combines a text box and a required field validator and have come across two solutions.
The first is from CodeProject and this control inherits from textbox
public class RequiredTextBox : TextBox {
private RequiredFieldValidator req;
protected override void OnInit(EventArgs e) {
req = new RequiredFieldValidator();
req.ControlToValidate = this.ID;
req.ErrorMessage = "You must enter something."
req.Text = "*";
Controls.Add(req);
}
protected override void Render(HtmlTextWriter w) {
base.Render(w);
req.RenderControl(w);
}
}
The second is from swarren.net and this control is a composite
public class RequiredTextField : Control, INamingContainer {
private TextBox textBox1;
#region Creating your child controls
protected override void CreateChildControls() {
textBox1 = new TextBox();
textBox1.ID = "textBox1";
textBox1.Text = Text;
RequiredFieldValidator validator1 = new RequiredFieldValidator();
validator1.ControlToValidate = "textBox1";
validator1.Text = "*";
validator1.ToolTip = validator1.ErrorMessage = "You must enter your name.";
validator1.Display = ValidatorDisplay.Dynamic;
Controls.Add(textBox1);
Controls.Add(new LiteralControl(" "));
Controls.Add(validator1);
}
public override ControlCollection Controls {
get {
EnsureChildControls();
return base.Controls;
}
}
#endregion
#region Text property
public string Text {
get {
if (textBox1 != null) {
return textBox1.Text;
}
string s = (string)ViewState["Text"];
if (s == null) {
return String.Empty;
}
return s;
}
set {
ViewState["Text"] = value;
if (textBox1 != null) {
textBox1.Text = value;
}
}
}
#endregion
}
}</code>The composite control required a lot more code and you also have to create a designer for it and add all the normal textbox control properties with design time attributes so that the control, looks and behaves exactly like the normal textbox. If you inherit from textbox however, you don't have to do any of this.
So are there any problems with the first solution. The reason I ask is that a number of server control professionals use the composite solution. I dont understand though, as the first solution is much simpler