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

car*_*666 2 c# asp.net

有没有办法引用动态创建的控件,例如一对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);
Run Code Online (Sandbox Code Playgroud)

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

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

任何帮助,将不胜感激.

Ste*_*n V 5

我想你可以做到这一点FindControl().您需要为代码隐藏中的那些文本框设置ID.

您可能PlaceHolder1rbList_SelectedIndexChanged活动中有参考.所以在活动中:

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