繁体   English   中英

如何引用动态创建的控件?

[英]How to reference dynamically created controls?

有没有办法引用动态创建的控件,例如一对TextBoxes和一个RadioButtonList,当用户单击按钮或更改选定的单选按钮时。

我需要将记录插入数据库,但我需要所有的值。 我不能对控件进行硬编码,因为它们必须在运行中创建。

TextBox t1 = new TextBox();
PlaceHolder1.Controls.Add(t1);

TextBox t2 = new TextBox();
PlaceHolder1.Controls.Add(t2);

RadioButtonList rbList = new RadioButtonList();
rbList.Items.Add(new ListItem("Today", "1"));
rbList.Items.Add(new ListItem("This Week", "2"));
rbList.SelectedIndexChanged += new EventHandler(rbList_SelectedIndexChanged);

PlaceHolder1.Controls.Add(rbList);

我需要在rbList_SelectedIndexChanged或其他一些事件中引用两个文本框和RadioButtonList。 将EventHandlers添加到文本框是不行的,因为我需要将所有三个值插入到数据库中。

我的初衷是以某种方式将texbox的引用传递给rbList_SelectedIndexChanged事件,但我不确定如何做到这一点,更不确定它是否会起作用。

任何帮助,将不胜感激。

我认为你可以用FindControl()完成这个任务。 您需要为代码隐藏中的那些文本框设置ID。

您可能在rbList_SelectedIndexChanged事件中引用了PlaceHolder1 所以在活动中:

var TextBox1 = (TextBox)Placeholder1.FindControl("{text box 1 ID here}");
var TextBox2 = (TextBox)Placeholder1.FindControl("{text box 2 ID here}");

创建UserControl以封装这些控件。 在内部放置一些逻辑以根据其值保存两个控件。 将此用户控件添加到PlaceHolder。 查看此文章以供进一步阅读

我的初衷是以某种方式将texbox的引用传递给bList_SelectedIndexChanged事件

这就是我要做的。 通过对可以关闭所需变量的事件处理程序使用匿名方法,可以轻松完成此操作:

rbList.SelectedIndexChanged += (s, e) =>selectionChangedHandler(rbList t1, t2);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM