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?
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.