How to dynamically generate combination of ASP.NET user controls?
-
01-07-2019 - |
Question
I have several user controls, let's say A
, B
, C
and D
. Based on some random input, I need to generate a combination of these. For e.g. if input is 2a3d1a2c
I need to show two of the A's, 3 D's after that, an A again, etc.
I will also need to stabilize clientid's in order for them to work correctly. Because each of these controls use their own ClientID
property to gather the inputs on themselves. For e.g. user control A internally generates an input named this.ClientID + "$input1"
, and gathers its input from request like Request[this.ClientID + "$input1"]
. Since there can be more than one A, each A needs to have the same (unique) ClientID
after postback in order to get correct inputs from request.
Solution
To add controls dynamically, you can use a panel as a place holder, say
<asp:Panel ID="ControlPlaceholder" runat="server" />
Then, on the server side, you can add objects to it like so:
int controlCount = 0;
...
TextBox newTextBox = TextBox();
newTextBox.ID = "ctl_" + controlCount++;
ControlPlaceholder.Controls.Add(newTextBox);
If you add the controls to it during your Page_Load event and use a consistent method of generating the controls' IDs (such as a the simple count above) then any viewstate or event bindings will be re-bound to the right object on a postback.