问题
I have a user control which contains several buttons, depending on the button pressed a different control is added to the page (lets say button 1 adds a TextBox, button2 adds a label).
I have code along the lines of:
protected void but1_click(object sender, EventArgs e)
{
TextBox tb = new TextBox();
tb.ID = "tb1";
paramsCtrlDiv.Controls.Add(tb);
}
protected void but2_click(object sender, EventArgs e)
{
Label lb = new Label();
lb.ID = "lb1";
paramsCtrlDiv.Controls.Add(lb);
}
I then have a third button (button3) to get all controls on the page and their values. (Assume each button is only clicked once for this example).
My problem is when button3 is pressed the paramsCtrlDiv.controls array doesn't contain the controls that have been added. I know I need to add these controls at Page_Load time on each postback. My issue is as I don't know exactly what controls the user has added I don't know what I want to add a Page_Load (there could be a text box, then label, just a label or just a tb), I can't control what the user presses.
I know I could store everything in the session but I'm not sure this is an elegant solution. There can also be several instances of this control on different tabs so each one has to correctly maintain it's own control collection
回答1:
Because you are doing this dynamically, you need a way of storing what your are doing so the server can recreate it with each PostBack
. If you don't want to use Session
, store the data in the ViewState
(which will persist with the page regardless of time). Create a List<YourControlObjects>
and make sure it is Serializable
and then store it in the ViewState
. You probably want to store the control type, location, etc. so that you can rebuild it on Page_Load
each time there is a PostBack
.
The problem comes down to you needing to maintain your own state for these dynamically created controls. This is just one suggestion but you could do this many different ways.
回答2:
I personally would handle this using a ListView
. Include all of the controls you need in the ItemTemplate
with Visible=false
and bind them to a small list stored in the viewstate. Programatically set the correct control visible on row databind.
Note you will have to collect your data in the controls and save it in your list before you rebind it.
来源:https://stackoverflow.com/questions/5871926/asp-net-dynamically-adding-controls-on-button-press-postback-issue