ASP.NET WebControl和页面-动态添加控件(如TextBox) [英] ASP.NET WebControl & Page - Adding controls (like TextBox) dynamically

查看:110
本文介绍了ASP.NET WebControl和页面-动态添加控件(如TextBox)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用文本框创建自定义服务器控件(WebControl).

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

我将asp.net文本框添加到CreateChildControls覆盖中的自定义控件中.在OnInit覆盖中,我将事件处理程序添加到TextBox.TextChanged.

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

一切正常,除了TextChanged从不触发.我查看了viewstate,看起来我的文本框从未将其Text属性保存在viewstate中.我尝试在各种地方(包括构造函数)设置Text,但没有任何效果.

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.

如何将TextBox动态添加到WebControl中以将其Text保存在viewstate中并触发TextChanged事件?

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

我将不胜感激后面的WebControl代码示例,其中动态添加了TextBox并触发了TextChanged事件.

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

推荐答案

对其进行了修复.动态控件必须在Init事件中创建并添加.必须为其分配一个没有特殊ASP.NET符号的ID(自定义ID内的'$'或':'会破坏内容).将控件添加到控件树后,必须分配所有属性.

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.

这是背后的Page代码的工作示例:

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";
}

用于OnInit覆盖中的WebControl放置初始化代码

for WebControl place init code in OnInit override

这篇关于ASP.NET WebControl和页面-动态添加控件(如TextBox)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆