In developing web applications using ASP.NET, there are situation that you need to dynamically create controls and retrieve their values. For example, you may need to generate X number of textboxes and later read the inputted value on them. On this article, I'll show you how to do that easily. One thing you should remember when dealing with Dynamic control is you should recreate it every time the page loads so it will be known to the other controls. Timing is everything. The most appropriate place to call the creation of controls is at Page_Load event which you will see on the following snippets of source codes. The Example project that I will use for this article will asked for number of dynamic textboxes to create. As the user click the "Create dynamic controls" button, the dynamic controls will be automatically created. The project also shows how to retrieve the content from these dynamic textboxes. Lets start from creating the function that will generate the controls dynamically.
private void CreateControls(int num)
{
TableRow row; //dynamic row
TableCell cell; //dynamic cell
for (int i = 1; i <= num; i++) //create X dynamic textbox
{
row = new TableRow();
cell = new TableCell();
//Dynamic Textbox
TextBox txt = new TextBox();
txt.ID = "txtDynamic" + i;
//txt.Text = "Dynamic Text";
cell.Controls.Add(txt);
row.Cells.Add(cell);
Table1.Rows.Add(row); //add dynamic to table
}
}
And then call this function at the Page_Load Event.
protected void Page_Load(object sender, EventArgs e)
{
//check if Textbox1 has a value; Textbox1 contains how many control to create dynamically
//Textbox1 will contain a value if user input some numbers on it and click button1
if (Request.Form["txtNumberOfControl"] != null)
{
//recreate controls each time the page loads
CreateControls(Convert.ToInt32(Request.Form["txtNumberOfControl"].ToString()));
}
if (!Page.IsPostBack)
{
}
}
To retrieve values from these dynamic controls, use this code.
private void RetrieveValue(Control parent)
{
TextBox txtDynamic1 = (TextBox)this.Page.FindControl("txtDynamic1");
TextBox txtContent = (TextBox)this.Page.FindControl("txtContent");
txtContent.Text = txtDynamic1.Text; //get the value from the first dynamic control.
}
There you have it! You can download the complete sample VS 2008 project from here.
Please feel free to post comments and questions.
To stay up-to-date on Coding Tips & Tricks, subscribe now.
0 comments:
Post a Comment