Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Dynamically create textboxes using ASP.NET and then save their values in Database?

Tags:

c#

asp.net

I am creating a survey site. I want to add the textboxes dynamically and then get their values in the database.

Now let's say I select 4 textboxes from the dropdown to be there dynamically.

Code on the Selection on dropdown :

     protected void NumDropDown_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (DropDownList1.SelectedValue == "TextBox")
        {

            int j;
            i = int.Parse(NumDropDown.SelectedValue);
            Session["i"] = i;
            switch (i)
            {
                case 1:
                    t = new TextBox[i];
                    Session["textBox"] = t;
                    for (j = 0; j < i; j++)
                    {
                        t[j] = new TextBox();
                        t[j].ID = "txtCheckbox" + j.ToString();
                        Panel1.Controls.Add(t[j]);

                    }
                    break;
                case 2:
                    t = new TextBox[i];
                    Session["textBox"] = t;
                    for (j = 0; j < i; j++)
                    {
                        t[j] = new TextBox();
                        t[j].ID = "txtCheckbox" + j.ToString();
                        Panel1.Controls.Add(t[j]);

                    }
                    break;

                case 3:
                    t = new TextBox[i];
                    Session["textBox"] = t;
                    for (j = 0; j < i; j++)
                    {
                        t[j] = new TextBox();
                        t[j].ID = "txtCheckbox" + j.ToString();
                        Panel1.Controls.Add(t[j]);

                    }
                    break;
                case 4:
                    t = new TextBox[i];
                    List<TextBox> MyTextBoxes;
                    for (j = 0; j < i; j++)
                    {
                        t[j] = new TextBox();
                        t[j].ID = "txtCheckbox" + j.ToString();
                        Panel1.Controls.Add(t[j]);
                        try
                        {
                            MyTextBoxes = (List<TextBox>)Session["AddedTextBox"];
                            MyTextBoxes.Add(t[j]);
                            Session["AddedTextBox"] = MyTextBoxes;
                        }
                        catch
                        {
                            MyTextBoxes = new List<TextBox>();
                            MyTextBoxes.Add(t[j]);
                            Session["AddedTextBox"] = MyTextBoxes;
                        }
                    }
                    break;
            }

        }
    }

2) Then Here I entered the values in the textBox like a, b,c,d and click ADD:

Code for the click On the ADD Click :

1) First i checked the session to be there on Page_Init :

    protected void Page_Init(object sender, EventArgs e)
    {
        if (Session["AddedTextBox"] != null)
        {
            string a;
            string b;
            string c;
            string d;

            int listCount = ((List<TextBox>)Session["AddedTextBox"]).Count;
            foreach (TextBox t in ((List<TextBox>)Session["AddedTextBox"]))
            {
                if (listCount == 1)
                {

                }
                if (listCount == 2)
                {

                }
                if (listCount == 3)
                {

                }
                if (listCount == 4)
                {
                    if (t.ID == "txtCheckbox0")
                    {
                        a = t.Text;
                    }
                    if (t.ID == "txtCheckbox0")
                    {
                        b = t.Text;
                    }
                    if (t.ID == "txtCheckbox0")
                    {
                        c = t.Text;
                    }
                    if (t.ID == "txtCheckbox0")
                    {
                        d = t.Text;
                    }

                }
            }
        }

But the problem here is that I don't get the text values, they Appear to be empty. Please help me to solve this issue.

like image 313
Prateik Avatar asked Feb 11 '13 16:02

Prateik


People also ask

How do you store values of dynamically created textboxes?

To get values of dynamically created controls on postback you need to recreate those controls on Page_Init event Then view state of those controls will be loaded and you will get controls and there values.

How can insert TextBox data in DataBase in asp net?

Use one query and use @ParamName : string sqlquery = "INSERT INTO [Users] (FirstName,LastName,UserName,Password) VALUES (@FirstName,@LastName,@UserName,@Password)"; SqlCommand command = new SqlCommand(sqlquery , connection); //FirstName*********** string firstName = FirstNameTextBox. Text; command. Parameters.


2 Answers

This sounds like the age-old classic problem with asp.net adding controls dynamically to a page.

The problem is to with viewstate and reconstruction of the controls on postback.

You need to run the same code that generated the controls on postback at the correct time in the page lifecycle to ensure postback values match server-side controls.

Of course if you want a hacky shortcut, access the Request.Form["textCheckbox" + index] values directly

A useful article on the subject.

like image 69
jenson-button-event Avatar answered Oct 17 '22 21:10

jenson-button-event


As @jenson-button-event mentioned you can access the TextBox values through Request.Form here's an example:

ASPX:

<asp:DropDownList ID="ddlTextBoxes" runat="server">
    <asp:ListItem Value="1" Text="1" />
    <asp:ListItem Value="5" Text="5" />
</asp:DropDownList>
<asp:Button ID="btnAdd" runat="server" Text="Add" OnClick="Add" /><br />
<asp:PlaceHolder ID="container" runat="server" Visible="false">
    <asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClick="Submit" />
</asp:PlaceHolder>

Code behind:

    protected void Add(object sender, EventArgs e)
    {
        int numOfTxt = Convert.ToInt32(ddlTextBoxes.SelectedItem.Value);
        var table = new Table();

        for (int i = 0; i < numOfTxt; i++)
        {
            var row = new TableRow();
            var cell = new TableCell();

            TextBox textbox = new TextBox();
            textbox.ID = "Textbox" + i;
            textbox.Width = new Unit(180);

            cell.Controls.Add(textbox);
            row.Cells.Add(cell);
            table.Rows.Add(row);
        }

        container.Controls.AddAt(0,table);
        container.Visible = true;
    }

    protected void Submit(object sender, EventArgs e)
    {
        var textboxValues = new List<string>();
        if (Request.Form.HasKeys())
        {
            Request.Form.AllKeys.Where(i => i.Contains("Textbox")).ToList().ForEach(i =>
                {
                    textboxValues.Add(Request.Form[i]);
                });
        }

        //Do something with the textbox values
        textboxValues.ForEach(i => Response.Write(i + "<br />"));
        container.Visible = false;
    }
like image 44
Denys Wessels Avatar answered Oct 17 '22 21:10

Denys Wessels