Problem with dinamically generated controls in ASP.NET (C#) , csharp , dynamically , generated , controls Viet Nam
  • 12 years ago
    Hello! I am trying to generate web controls dynamically (running at server). In my page, I have a button to submit value of controls I've created (such as textbox, checkbox), my code is below: protected void dynamicControls() { con = data.GetConnection(); con.Open(); com.Connection = con; com.CommandText = "Type_GetAll"; reader = com.ExecuteReader(); table.Load(reader); double i=0,d=0,c=0; foreach (DataRow row in table.Rows) { i++; Label lit = new Label(); TextBox txt = new TextBox(); lit.ID = "lit" + i.ToString(); lit.Text = row.ItemArray[1].ToString(); lit.Visible = true; lit.Style["Position"] = "Absolute"; lit.Style["Top"] = c + "px"; lit.Style["Left"] = d + "px"; txt.ID = "txt" + i.ToString(); txt.Text = row.ItemArray[1].ToString(); txt.Style["Position"] = "Absolute"; txt.Style["Top"] = c + "px"; txt.Style["Left"] = Convert.ToString(d + lit.Text.Length*7) + "px"; c += 100; form1.Controls.Add(txt); form1.Controls.Add(lit); } con.Close(); } But when I run the web page, the controls is ok, verything is ok until I click the button. I dont know how to get the controls value that I've just created. Because when I click the button, I must write code in the Button_Click() function. And therefore, I can not get the local variables above in the FOR loop area. Do you know how to solve this problem. I am really appreciated your help. Goodluck to all and wish you a merry christmas!
  • 12 years ago
    hi, Place your controls on a panel or a div control and make this control a web control(runat=server). Then you can loop through all the controls you have created and check the control type. Accordingly you can get the ID of the control and also the value. Regards, Royal
  • 12 years ago
    Also please wrap your posted code in the CODE tags, currently this is not readable. A wild guess could be to find the control. Royal is right you should better put it in some panel and then use the FindControl method of panel to find that newly added control.

Post a reply

Enter your message below

Sign in or Join us (it's free).


Why not write for us? Or you could submit an event or a user group in your area. Alternatively just tell us what you think!

Our tools

We've got automatic conversion tools to convert C# to VB.NET, VB.NET to C#. Also you can compress javascript and compress css and generate sql connection strings.

“Java is to JavaScript what Car is to Carpet.” - Chris Heilmann