ASP.NET Web 控件和 页面 - 动态添加控件(如 TextBox)
我正在尝试创建带有文本框的自定义服务器控件(WebControl)。
我将 asp.net 文本框添加到 CreateChildControls 覆盖中的自定义控件。 在 OnInit 重写中,我将事件处理程序添加到 TextBox.TextChanged。
一切正常,除了 TextChanged 永远不会触发。 我查看了视图状态,看起来我的文本框从未将其 Text 属性保存在视图状态中。 我尝试在不同的地方设置文本,包括构造函数,但没有任何效果。
如何将 TextBox 动态添加到 WebControl 以将其文本保存在视图状态中并触发 TextChanged 事件?
我非常感谢后面的 WebControl 代码示例,其中动态添加 TextBox 并触发 TextChanged 事件。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
必须在每次回发中再次创建动态创建的控件(pageInit 事件是更好的选择)才能触发该事件。
顺便说一句,如果您希望 TextChanged 事件生成回发,您还必须将控件的 AutoPostback 设置为 true。
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.
修复。 必须在 Init 事件中创建并添加动态控件。 必须为其分配一个不带特殊 ASP.NET 符号的 ID(自定义 ID 内的“$”或“:”会破坏内容)。 将控件添加到控件树后,必须分配所有属性。
这是页面代码隐藏的工作示例:
对于 WebControl,将初始化代码放在 OnInit 覆盖中
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:
for WebControl place init code in OnInit override
这将帮助你。 简而言之,您需要自己处理动态添加的控件的视图状态。
This will help you out. In short, you need to handle the viewstate for your Dynamically added control on your own.