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
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;
}
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.