hi, i m asha bhatt.
plz look at this my code
i have declare this first :-

CheckBox chkList1; 
 protected void Page_Load(object sender, EventArgs e)
    {
    }
 protected void NextQuestionButton_Click(object sender, EventArgs e)
    {
        createcheckbox();
}
 public void createcheckbox()
    {
        Response.Write("asha");
        chkList1 = new CheckBox();

        chkList1.Text = "strCheckboxText";

        chkList1.ID = "Chk";

        chkList1.Font.Name = "Verdana";

        chkList1.Font.Size = 9; 

    }

I have button Next , when i will click on the next button then dynamically checkbox should create , which i cant do it.
Plz help me

Dani AI

Generated

Short diagnosis and a practical pattern to fix this thread's problems.

is creating controls only on a button click and not recreating them on subsequent postbacks, using the same ID for every dynamic control, and wiring the wrong event (TextChanged) for a CheckBoxList. is right that Page_Load can be used to add controls, but the reliable place to recreate dynamic controls so ViewState and events work is Page_Init (or at least before LoadViewState). Also avoid a static DataTable for per-user data — that will be shared across sessions; use Session or reload per request.

Use one CheckBoxList per question (with four ListItems for Option1..Option4), persist the current question index in ViewState, and recreate the CheckBoxList on every page lifecycle (Page_Init). Example pattern:

int CurrentQuestionIndex {
  get { object o = ViewState["QIndex"]; return o==null?0:(int)o; }
  set { ViewState["QIndex"] = value; }
}

protected void Page_Init(object sender, EventArgs e) {
  RecreateQuestionControls();
}

void RecreateQuestionControls() {
  Panel1.Controls.Clear();
  if (dt == null || CurrentQuestionIndex >= dt.Rows.Count) return;
  var row = dt.Rows[CurrentQuestionIndex];
  var cbl = new CheckBoxList { ID = "cblQ" + CurrentQuestionIndex, AutoPostBack = false };
  cbl.Items.Add(new ListItem(row["Option1"].ToString(),"1"));
  cbl.Items.Add(new ListItem(row["Option2"].ToString(),"2"));
  cbl.Items.Add(new ListItem(row["Option3"].ToString(),"3"));
  cbl.Items.Add(new ListItem(row["Option4"].ToString(),"4"));
  Panel1.Controls.Add(cbl);
  QuestionLabel.Text = row["Question"].ToString();
}

protected void NextQuestionButton_Click(object sender, EventArgs e) {
  CurrentQuestionIndex++;
  RecreateQuestionControls();
}

Troubleshooting notes: use named columns (e.g. row["Option2"]) instead of numeric indexes, give each dynamic control a unique stable ID, wire SelectedIndexChanged + AutoPostBack=true if you need immediate server handling, and avoid calling event handlers directly from Page_Load.

Recommended Answers

All 4 Replies

Choose page_load() event to add controls dynamically.

protected void Page_Load(object sender, EventArgs e)
    {
       CheckBox cx=new CheckBox();
       ...
       form1.Controls.Add(cx);
    }

plz look at my code give me the solucation

protected void Page_Load(object sender, EventArgs e)
    {
         createcheckboxList();
}
public void createcheckboxList()
    {
        for (int i = 0; i < 4; i++)
        {
            //CheckBox chk = new CheckBox();
            ////chk.AutoPostBack = true;
            //chk.ID = "chk" + 1;
            //chk.Text = "asha";
            //chk.CheckedChanged += new EventHandler(chk_CheckedChanged);
            //Panel1.Controls.Add(chk);

            CheckBoxList chklist = new CheckBoxList();
            chklist.ID = "chklist" + 1;
            chklist.Text = "nitin";
            chklist.TextChanged += new EventHandler(chklist_TextChanged);
            Panel1.Controls.Add(chklist);

            
        }

    }

it giving me error.
Plz help me...................

hi,
plz look at my code and give me the solution

using System.Data.SqlClient;
using System.Diagnostics;

public partial class Default2 : System.Web.UI.Page
{
    string scon = "Data Source=RBWORKSTATION2\\SQLEXPRESS;Initial Catalog=onlineexamdb;Integrated Security=True;MultipleActiveResultSets=true";
    SqlConnection con;
    SqlDataAdapter da;
    SqlCommand cmd;
    DataSet ds;
    static DataTable dt;
    IDataReader readqus;
    public string qus;
    static int count = 0;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            getquestion();
            NextQuestionButton_Click(sender, e);
        }
      
    }

    public string getquestion()
    {
        con = new SqlConnection(scon);
        con.Open();
        if (!IsPostBack)
        {
            cmd = new SqlCommand("SELECT  QusID , SubjectName , Question , Option1 ,Option2,Option3,Option4 from SubjectInfo INNER JOIN Questions ON SubjectInfo.SubID = Questions.SubID ", con);
            dt = new DataTable();
            readqus = cmd.ExecuteReader();
            if (readqus != null)
            {
                dt.Load(readqus);
            }
        }
        
        createcheckbox();
        con.Close();
        return "true";
       
    }
 public void createcheckbox()
    {
for (int intControlIndex = 0; intControlIndex < 4; intControlIndex++)
        {
            
            if (count < dt.Rows.Count)
            {
                chklist.ID = "chklist" + 1;
                chklist.Items.Add(new ListItem(dt.Rows[count][3].ToString()));
                //chklist.Attributes.Add("runat", "server");
                chklist.RepeatDirection = RepeatDirection.Vertical;
                chklist.TextChanged += new EventHandler(chklist_TextChanged);
                Panel1.Controls.Add(chklist);

                count = count + 1;
            }
            else
            {
                Response.Write("<script>alert('Your Test is finished')</script>");
            }
        } 
    }
 void chklist_TextChanged(object sender, EventArgs e)
    {
        Response.Write("Create CheckBoxList");
    }
protected void NextQuestionButton_Click(object sender, EventArgs e)
    {
     createcheckbox();
     try
        {
            if (count < dt.Rows.Count)
            {
                QuestionLabel.Text = dt.Rows[count][2].ToString();

                count = count + 1;
            }
            else
            {
                Response.Write("<script>alert('Your Test is finished')</script>");
            }

          }
        catch (IndexOutOfRangeException ex)
        {
          // Response.Write(ex.Message);
        }
    }

in my query i have option1 , 2 ,3 4. these options value i want show in checkboklist one by one means checkboxlist 1 will show option1 value , checkboxlist 2 will show option2 value , checkboxlist3 will show option3 value etc , but when i m doing this i m not getting correct output. it read but show only option1 value in all checkboxlist.

Plz help me..............

Please read the rules before posting again, in particular the 'keep it organized' one -

  1. Do not flood the forum by posting the same question more than once (ie in multiple forums).
  2. For easy readability, always wrap programming code within posts in [code] (code blocks) and [icode] (inline code) tags.

If you hit 10 infraction points your account gets an automatic ban, so it is worth obeying the rules if you want to continue to benefit from DaniWeb 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.