Custom WebControl and Postback

1.9k Views Asked by At

I'm trying to create a few custom web controls wrapping some existing controls. One of them, for instance, is a wrap for a textbox (because I need additional behaviors such as corresponding validators). The problem is, I'm not sure how to get the data of that control to be sent in the postback.

A very simplified example:

public class MyTestBox: WebControl
{
protected TB { get; set; }
public Text
{
    get { return TB.Text; }
    set { TB.Text = value; }
}
protected override void CreateChildControls()
{
TB= new TextBox()
Controls.Add(TB);
}
}

But if I now test a webform with the control:

<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<bleh:MyTextBox ID="MyTextBox1" runat="server" />
<asp:Button ID="Button1" runat="server" Text="Submit" />

Then after entering text into the textboxes and submitting, the text in TextBox1 is available in Page_Load, while MyTextBox1.Text is empty. What should I change to have its content available when sending a postback?

Edit:

Something I thought of now is to simply check the request form when initializing the control:

protected override void OnInit(EventArgs e)
{
    TB.ID = this.ID + "_TextBox1";
    Controls.Add(TB);
    if (Page.Request.Form[TB.UniqueID] != null)
    {
         Text = Page.Request.Form[TB.UniqueID];
    }
}

It seems to be working, but feels sort of hacky. Does this seem like a reasonable way?

3

There are 3 best solutions below

0
On

You should give the dynamically generated TextBox an ID, then on the Text property of your control, you should find the TextBox and return its Text.

public class BksTextBox: WebControl
{
protected TB { get; set; }
public Text
{
    get 
    { 
       return ((TextBox)this.FindControl("txt")).Text;
    }
}
protected override void CreateChildControls()
{
TB= new TextBox()
TB.ID = "txt";
Controls.Add(TB);
}
}
2
On

I was not getting your question. If you need to add some extra behaviour to a web control you should do the same thing you would do in the case you want extend a class behaviour that is inheritance. you can Inherits straigh form the TextBox class and add all the extra behaviour you need

 public class BksTextBox: TextBox
  {
    //it is just as example
    public string TextToUpperCase
    {
    get
      {
       return Text.ToUpperCase();
       }
     }

}
0
On

It could have something to do with the Page life cycle. Try to use this.EnsureChildControls() in the Text property getter. More on the Page life cycle can be found in MSDN documentation.