I have to create a number of controls equal to a number entered in a textbox by the user. I created a web user control, which has a radio button list. Then when the user press a Submit button, I want to check the selected values of the controls created dynamically, but the problem is that they are removed on post-back.

I managed with the aid of an article I read on the net (http://www.tgreer.com/aspnet_html_04.html), to maintain the controls created dynamically after post back, but still one problem I have is the values the user enters in the dynamically created controls is lost after post back.

Here is my code:

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
 
public partial class questions : System.Web.UI.Page
{
void Page_Load(object sender, EventArgs e)
{
    if (!=IsPostBack)
    {
       ViewState.Add("mode", "0");
    }
}
protected override void LoadViewState(object savedState)
{
      base.LoadViewState(savedState);
      if (ViewState["mode"].ToString() == "1")
      {
         CreateControls();
      }
}
protected void BTN_Submit_Click(object sender, EventArgs e)
{
    if (TextBox1.Text != "")
   {
       for (int i = 0; i < int.Parse(TextBox1.Text); i++)
       {
           ASP.mcq_ascx newc = new ASP.mcq_ascx();
           newc.ID = "newc" + i.ToString();
           this.Q_PlaceHolder.Controls.Add(newc);
        }
    }
}
protected void BTN_Result_Click(object sender, EventArgs e)
{
    CreateControls();
    ViewState.Add("mode", "1");
}
protected void CreateControls()
{
     if (TextBox1.Text != "")
     {
          for (int i = 0; i < int.Parse(TextBox1.Text); i++)
          {
               ASP.mcq_ascx newc = new ASP.mcq_ascx();
               newc.ID = "newc" + i.ToString();
               this.Q_PlaceHolder.Controls.Add(newc);
           }
      }
 }
}

you should beable to get their values with Request.Form["fieldName"]

thanks for your help :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.