ASP.NET WebControl & Page - Adding controls (like TextBox) dynamically

被刻印的时光 ゝ 提交于 2019-12-11 05:35:23

问题


I'm trying to create a custom server control (WebControl) with a text box.

I add asp.net textbox to the custom control in CreateChildControls override. In OnInit override I add event handler to TextBox.TextChanged.

Everything works, except that TextChanged never fires. I looked at viewstate and it looks like my textbox never saves its Text property in the viewstate. I've tried to set Text in various places, including constructor, but nothing works.

How can I get TextBox dynamically added to WebControl to save it's Text in viewstate and get TextChanged event to fire?

I would greatly appreciate an example of WebControl code behind with TextBox being added dynamically and TextChanged event being fired.


回答1:


The dynamically created control must be created again in each post back, (the pageInit event is the better option) for the event to be fired.

BTW, if you want the TextChanged event to generate a postback you must also set the AutoPostback of the control to true.




回答2:


fixed it. dynamic control must be created and added in Init event. It must be assigned an ID without special ASP.NET symbols ('$' or ':' inside custom ID will break things). All properties must be assigned after control is added to the controls tree.

here's a working example for Page codebehind:

private readonly TextBox _textBoxTest = new TextBox();

protected void Page_Init( object sender, EventArgs e )
{
    this.form1.Controls.Add( _textBoxTest ); 
    _textBoxTest.Text = "TestBoxTest";
    _textBoxTest.ID = "TestBoxTestId";
    _textBoxTest.TextChanged += this._textBoxTest_TextChanged;
}

void _textBoxTest_TextChanged( object sender, EventArgs e )
{
    _textBoxTest.Text = "Worked";
}

for WebControl place init code in OnInit override




回答3:


This will help you out. In short, you need to handle the viewstate for your Dynamically added control on your own.



来源:https://stackoverflow.com/questions/1028905/asp-net-webcontrol-page-adding-controls-like-textbox-dynamically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!