Dynamically/Run Time Create Control and access the Entered value
Posted by dotnetsharepointwatever on October 23, 2008
There will be a time when you need to create a control (textbox/dropdownlist/label) dynamically.
Then what you need to do is.
1. Add a panel into your form
2. Create code behind that generate the control, and put it into the panel.
3. CALL THE CONTROL GENERATE PART EVERY POST BACK
You need to generate the control every page post back, otherwise the control wont be there after post back.
But don’t worry about the value of the control, it will wont disappear, it will still be there, it’s being store in the viewstate.
Since code speaks thousand words, Please take a look at the code below :
- Default.aspx.cs
protected void Page_Init(object sender, EventArgs e)
{
GenerateControl();
}
private void GenerateControl()
{
Panel1.Controls.Clear ();
Table tbl = new Table();
tbl.ID = “table123″;
for ( int i = 0 ; i < NumberOfControl ; i++ )
{
TableRow tr = new TableRow();
// creating label
TableCell tc = new TableCell();
Label lbl = new Label();
lbl.Text = “Value ” + (i+1).ToString();
tc.Controls.Add(lbl);
tr.Cells.Add(tc);
tc = new TableCell();
lbl = new Label();
lbl.Text = “:”;
tc.Controls.Add(lbl);
tr.Cells.Add(tc);
// creating txtbox
tc = new TableCell();
TextBox txt = new TextBox();
txt.ID = “DynamicTextBox” + i.ToString();
tc.Controls.Add(txt);
tr.Cells.Add(tc);
tbl.Rows.Add(tr);
}
Panel1.Controls.Add(tbl);
}
protected void BtnGetValue_Click(object sender, EventArgs e)
{
string Value = string.Empty;
Table tbl = (Table)Panel1.FindControl(“table123″);
for (int i = 0; i < NumberOfControl ; i++)
{
TextBox txt = (TextBox ) tbl.FindControl(“DynamicTextBox” + i.ToString());
Value = Value + txt.Text + ” “;
}
Label1.Text = Value;
}
protected void BtnGenerateControl_Click(object sender, EventArgs e)
{
NumberOfControl = Int32.Parse(DropDownList1.SelectedValue);
GenerateControl();
}
}
}
or, download the whole solution code here