Click here to Skip to main content
15,881,812 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
C#
i m trying to add textbox dynamically at runtime and saving data in sql server. i am able generate textbox but not able send data in database and it is not giving any error also. what i am doing wrong? here is my code

What I have tried:

protected void btnAddCtrl_Click(object sender, EventArgs e)
{
    int rowCount = 0;

    //initialize a session.
    rowCount = Convert.ToInt32(Session["clicks"]);

    rowCount++;

    //In each button clic save the numbers into the session.
    Session["clicks"] = rowCount;


    //Create the textboxes and labels each time the button is clicked.
    for (int i = 0; i < rowCount; i++)
    {

        TextBox TxtBoxU = new TextBox();

        //TextBox TxtBoxE = new TextBox();

        Label lblU = new Label();
       // Label lblE = new Label();

        TxtBoxU.ID = "TextBoxU" + i.ToString();
      //  TxtBoxE.ID = "TextBoxE" + i.ToString();

        lblU.ID = "LabelU" + i.ToString();
       // lblE.ID = "LabelE" + i.ToString();


        lblU.Text = "User " + (i + 1).ToString() + " : ";
       // lblE.Text = "E-Mail : ";

        //Add the labels and textboxes to the Panel.
        Panel1.Controls.Add(lblU);
        Panel1.Controls.Add(TxtBoxU);
        Panel1.Controls.Add(new LiteralControl("<br />"));
        Panel1.Controls.Add(new LiteralControl("<br />"));




    }


}


protected void btnSave_Click(object sender, EventArgs e)
{
    foreach (TextBox textBox in Panel1.Controls.OfType<textbox>())
    {
        string constr = ConfigurationManager.ConnectionStrings["myconnectionstring"].ConnectionString;
        using (SqlConnection con = new SqlConnection(constr))
        {
            using (SqlCommand cmd = new SqlCommand("INSERT INTO AssetsDetail (FieldName) VALUES(@FieldName)",con))
            {
                cmd.Connection = con;
                cmd.Parameters.AddWithValue("@FieldName", textBox.Text);
                con.Open();
                cmd.ExecuteNonQuery();
                con.Close();
            }
        }
    }
}</textbox>
Posted
Updated 14-Jun-22 22:07pm

1 solution

try this.
inspired from ASP.Net Persist Dynamic Controls: Dynamic Controls disappear after PostBack in ASP.Net[^]

C#
public partial class WebForm1 : System.Web.UI.Page
   {
       protected void Page_Load(object sender, EventArgs e)
       {


       }

       protected void btnAddCtrl_Click(object sender, EventArgs e)
       {
           int rowCount = 0;
           rowCount = Convert.ToInt32(Session["clicks"]);
           rowCount++;
           Session["clicks"] = rowCount;
           int i = rowCount;

           TextBox TxtBoxU = new TextBox();
           Label lblU = new Label();
           TxtBoxU.ID = "TextBoxU" + i.ToString();
           lblU.ID = "LabelU" + i.ToString();
           lblU.Text = "User " + i.ToString() + " : ";
           Panel1.Controls.Add(lblU);
           Panel1.Controls.Add(TxtBoxU);


       }

       protected void Page_PreInit(object sender, EventArgs e)
       {
           List<string> keys = Request.Form.AllKeys.Where(key => key.Contains("TextBoxU")).ToList();
           foreach (string key in keys)
           {
               string id = key.Replace("TextBoxU", "");
               this.CreateTextBox(key, "LabelU" + id ,   id);

           }
       }

       private void CreateTextBox(string id, string labelId,string idNo )
       {

           Label lbl = new Label();
           TextBox txt = new TextBox();
           txt.ID = id;
           lbl.ID = labelId;
           lbl.Text = "User " + idNo + " : ";
           Panel1.Controls.Add(lbl);
           Panel1.Controls.Add(txt);

       }

       protected void btnSave_Click(object sender, EventArgs e)
       {

           foreach (TextBox textBox in Panel1.Controls.OfType<TextBox>())
           {
               string text = textBox.Text;
               // your code to insert into database
           }
       }
   }
 
Share this answer
 
Comments
Zain Ul Abdin 22-May-16 13:57pm    
hi! i am using this code.but i am getting error"Object reference not set to an instance of an object." while adding second control .

Line 48: lbl.ID = labelId;
Line 49: lbl.Text = "User " + idNo + " : ";
Line 50: Panel1.Controls.Add(lbl);
Line 51: Panel1.Controls.Add(txt);
Line 52:

at line 50
Karthik_Mahalingam 22-May-16 14:00pm    
Just create a new page with a panel and 2 buttons and copy paste this code
It should work.
I have tested it
Zain Ul Abdin 23-May-16 3:57am    
i did exactly the same thing. but it is giving error while adding second control. it works fine while adding only ONE control
Karthik_Mahalingam 23-May-16 4:03am    
post your code.
here
Karthik_Mahalingam 23-May-16 4:08am    
try this
aspx:
<form id="form1" runat="server">
<div>

<asp:Panel runat="server" ID="Panel1">
<asp:Button Text="AddCtrl" ID="btnAddCtrl" runat="server" OnClick="btnAddCtrl_Click" />
<asp:Button Text="Save" ID="btnSave" runat="server" OnClick="btnSave_Click" />

</div>
</form>

cs:

public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{


}

protected void btnAddCtrl_Click(object sender, EventArgs e)
{
int rowCount = 0;
rowCount = Convert.ToInt32(Session["clicks"]);
rowCount++;
Session["clicks"] = rowCount;
int i = rowCount;

TextBox TxtBoxU = new TextBox();
Label lblU = new Label();
TxtBoxU.ID = "TextBoxU" + i.ToString();
lblU.ID = "LabelU" + i.ToString();
lblU.Text = "User " + i.ToString() + " : ";
Panel1.Controls.Add(lblU);
Panel1.Controls.Add(TxtBoxU);


}

protected void Page_PreInit(object sender, EventArgs e)
{
List<string> keys = Request.Form.AllKeys.Where(key => key.Contains("TextBoxU")).ToList();
foreach (string key in keys)
{
string id = key.Replace("TextBoxU", "");
this.CreateTextBox(key, "LabelU" + id, id);

}
}

private void CreateTextBox(string id, string labelId, string idNo)
{

Label lbl = new Label();
TextBox txt = new TextBox();
txt.ID = id;
lbl.ID = labelId;
lbl.Text = "User " + idNo + " : ";
Panel1.Controls.Add(lbl);
Panel1.Controls.Add(txt);

}

protected void btnSave_Click(object sender, EventArgs e)
{

foreach (TextBox textBox in Panel1.Controls.OfType<textbox>())
{
string text = textBox.Text;
// your code to insert into database
}
}


}
}

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900