I created some textbox and I want to get their value dynamically. Briefly, ı explain my page:
I have dropDown list has number 1 to 15.When the user select number and I
Below code will help you
protected void ddlUserSelected_SelectedIndexChanged(object sender, EventArgs e)
{
for (int a = 1; a <= int.Parse(ddlUserSelected.SelectedItem.Text); a++)
{
TextBox txtDate = new TextBox();
Label lbl = new Label();
lbl.Text = "<br/>";
txtDate.Width = 70;
txtDate.CssClass = "tbl";
txtDate.ID = "txtDate" + a;
PlaceHolder1.Controls.Add(txtDate);
PlaceHolder1.Controls.Add(lbl);
}
}
protected void btnSave_Click(object sender, EventArgs e)
{
for (int a = 1; a <= int.Parse(ddlUserSelected.SelectedItem.Text); a++)
{
if(Request.Form.Get("txtDate" + a.ToString()) != null)
{
var str = Request.Form.Get("txtDate" + a.ToString());
}
}
}
If you are used master page then use below code
if (Request.Form.Get("ctl00$ContentPlaceHolder1$txtDate" + a.ToString()) != null)
{
var str = Request.Form.Get("ctl00$ContentPlaceHolder1$txtDate" + a.ToString());
}
protected void btnSave_Click(object sender, EventArgs e)
{
for (int a = 1; a <= int.Parse(ddlUserSelected.SelectedItem.Text); a++)
{
string value = Request.Form["txtDate" + a];
}
}
If you dynamically add controls to a page, you need to reloaded them on Page Init or Page Load.
Otherwise, you won't be able to find them when you post back.
<asp:DropDownList ID="ddlUserSelected" AutoPostBack="true"
OnSelectedIndexChanged="ddlUserSelected_SelectedIndexChanged"
runat="server">
<asp:ListItem Text="Select one" />
<asp:ListItem Text="1" />
<asp:ListItem Text="2" />
<asp:ListItem Text="3" />
<asp:ListItem Text="4" />
<asp:ListItem Text="5" />
</asp:DropDownList>
<br/>
<asp:PlaceHolder ID="PlaceHolder1" runat="server"/>
<asp:Button ID="btnSave" runat="server" Text="Save" OnClick="btnSave_Click" />
private int Total
{
get
{
int total;
if (Int32.TryParse(ddlUserSelected.SelectedItem.Text, out total))
return total;
return 0;
}
}
protected void Page_Load(object sender, EventArgs e)
{
CreateTextBoxes(Total);
}
protected void ddlUserSelected_SelectedIndexChanged(object sender, EventArgs e)
{
CreateTextBoxes(Total);
}
protected void btnSave_Click(object sender, EventArgs e)
{
int total = Total;
for (int a = 1; a <= total; a++)
{
var textbox = PlaceHolder1.FindControl("txtDate" + a) as TextBox;
}
}
private void CreateTextBoxes(int total)
{
for (int a = 1; a <= total; a++)
{
// Make sure we do not add same ID again
if (PlaceHolder1.FindControl("txtDate" + a) == null)
{
TextBox txtDate = new TextBox();
Label lbl = new Label();
lbl.Text = "<br/>";
txtDate.Width = 70;
txtDate.CssClass = "tbl";
txtDate.ID = "txtDate" + a;
PlaceHolder1.Controls.Add(txtDate);
PlaceHolder1.Controls.Add(lbl);
}
}
}