当用户单击按钮或更改选定的单选按钮时,是否有办法引用动态创建的控件,例如几个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。

您可能在PlaceHolder1事件中引用了rbList_SelectedIndexChanged。因此,在事件中:

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

关于c# - 如何引用动态创建的控件?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/16592956/

10-12 12:49
查看更多