Sunday, February 20, 2011

Dynamically generate button or Textbox according to the data in database in asp.net

 For generating dynamic button and textbox according to data present in database
if(!IsPostBack)
       {string[] nm=new string[100];
            SqlConnection con = new SqlConnection("connection string....");
            SqlCommand cmd = new SqlCommand("sql query.....", con);
            con.Open();
            SqlDataReader dr = cmd.ExecuteReader();
            int cnt = 0;
            int c=0;
            while (dr.Read())
            {
                cnt++;
                nm[c]=dr[0].ToString();
                c=c+1;
              }
            con.Close();
                
                for (int i = 0; i < cnt; i++)
                {
                    Button btn = new Button();                        TextBox txt = new TextBox();
                    btn.Text = nm[i];
                     btn.ID = i + "id";                                       txt.ID = i + "txt";
                     form1.Controls.Add(btn);                        txt.Width = 16;
                                                                                     txt.Height = 16;
                                                                                     txt.BorderStyle = BorderStyle.None;
                                                                                  //   txt.Enabled = false;
                                                                                        form1.Controls.Add(txt);
                }
                      
       }
it will generate the dynamic button and textbox according to data present in table

No comments:

Post a Comment