简体   繁体   中英

How to reference dynamically created controls?

Is there a way to reference dynamically created controls, such as a couple TextBoxes and maybe a RadioButtonList when the user either click a button or changes the selected radio button.

I need to insert a record into a database but I need all of the values. I cannot hard-code the controls because they must be created on the fly.

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);

I need to reference the two textboxes and the RadioButtonList within rbList_SelectedIndexChanged or some other event. Adding EventHandlers to the textboxes do my no good because I need all three values to insert into the database.

My inital thought was to somehow pass reference of the texboxes to the rbList_SelectedIndexChanged event but I am unsure of how to do this and even more unsure if it will even work.

Any help would be appreciated.

I think you could accomplish this with FindControl() . You'll want to set an ID to those text boxes in the code behinds.

You probably have a reference to PlaceHolder1 within the rbList_SelectedIndexChanged event. So within the event:

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

Create a UserControl to encapsulate these controls. Put some logic inside to save both controls depending on their values. Add this user control to the PlaceHolder. View this article for further reading

My inital thought was to somehow pass reference of the texboxes to the bList_SelectedIndexChanged event

That's what I'd do. This is easily done by using an anonymous method for the event handler that can close over the needed variables:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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