Saturday, March 24, 2012

Simple composite control with TextBox and Validator

I have the following simple composite control.

public class MyTextBox : CompositeControl {private TextBox textbox;private RequiredFieldValidator validator;public string Text {get { EnsureChildControls();return textbox.Text; }set { EnsureChildControls(); textbox.Text =value; } }public string ValidationGroup {get { EnsureChildControls();return validator.ValidationGroup; }set { EnsureChildControls(); validator.ValidationGroup =value; } }protected override void CreateChildControls() { Controls.Clear(); textbox =new TextBox(); textbox.ID ="textbox"; Controls.Add(textbox); validator =new RequiredFieldValidator(); validator.ID ="valInput"; validator.ControlToValidate = textbox.ID; validator.ErrorMessage ="*"; validator.Display = ValidatorDisplay.Static; Controls.Add(validator); }protected override void RenderContents(HtmlTextWriter writer) { textbox.RenderControl(writer); validator.RenderControl(writer); }protected override HtmlTextWriterTag TagKey {get {return HtmlTextWriterTag.Span; } } }

and if I load this control on web form like below, It works fine.

<cc:MyTextBox ID="MyTextBox1" runat="server" />
<asp:Button ID="Button1" Text="PostBack" runat="server" />

but if I set ValidationGroup property, fill TextBox with something and click the button, the validation error occurs.

<cc:MyTextBox ID="MyTextBox1" ValidationGroup="A" runat="server" />
<asp:Button ID="Button1" Text="PostBack" ValidationGroup="A" runat="server" />

I found that calling EnsureChildControls() inside the setter of ValidationGroup property causes the problem.
If I call EnsureChildControls() in the constructor, everything works fine.
But as I know, calling EnsureChildControls() in the property and not in the constructor is also a common practice.
So I wonder why the above code doesn't work well.

have look here

similar to urs

http://www.samspublishing.com/articles/article.asp?p=101748&seqNum=5&rl=1


textbox =new TextBox();textbox.ID ="textbox";Controls.Add(textbox);validator =new RequiredFieldValidator();validator.ID ="valInput";validator.ControlToValidate = textbox.ID;validator.ErrorMessage ="*";validator.Display = ValidatorDisplay.Static;Controls.Add(validator);

I changed the above code like below.

textbox =new TextBox();textbox.ID ="textbox";validator =new RequiredFieldValidator();validator.ID ="valInput";validator.ControlToValidate = textbox.ID;validator.ErrorMessage ="*";validator.Display = ValidatorDisplay.Static;Controls.Add(textbox);Controls.Add(validator);

And the problem disappeared.
But I dodn't know why the original code causes the problem.

0 comments:

Post a Comment