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

后端 未结 2 1687
忘掉有多难
忘掉有多难 2020-12-20 18:53

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 dropdow

2条回答
  •  天涯浪人
    2020-12-20 19:29

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

    ASPX:

    
        
        
    
    

    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();
            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 + "
    ")); container.Visible = false; }

提交回复
热议问题