for creating dynamic controls in asp.net , we should take panel control, write the code in default.aspx source
default.aspx file
<div>
<asp:Panel ID="pnlinfo" runat="server" Height="36px" Width="1349px">
</asp:Panel>
</div>
default.aspx.cs file
protected void Page_Load(object sender, EventArgs e)
{
Table tbldynamic = new Table();
TableCell tc = new TableCell();
TableCell tc1 = new TableCell();
TableRow tr = new TableRow();
Label lblName = new Label();
lblName.ID = "lblName";
lblName.Text = "UserName:";
tc.Controls.Add(lblName);
TextBox txtName = new TextBox();
txtName.ID = "txtName";
tc1.Controls.Add(txtName);
tr.Cells.Add(tc);
tr.Cells.Add(tc1);
tbldynamic.Rows.Add(tr);
tc = new TableCell();
tc1 = new TableCell();
tr = new TableRow();
Label lblEmail = new Label();
lblEmail.ID = "lblEmail";
lblEmail.Text = "Email:";
tc.Controls.Add(lblEmail);
TextBox txtEmail = new TextBox();
txtEmail.ID = "txtEmail";
tc1.Controls.Add(txtEmail);
tr.Cells.Add(tc);
tr.Cells.Add(tc1);
tbldynamic.Rows.Add(tr);
tc = new TableCell();
tc1 = new TableCell();
tr = new TableRow();
Button btnSubmit = new Button();
btnSubmit.ID = "btnSubmit";
btnSubmit.Text = "Submit";
btnSubmit.Click += new System.EventHandler(btnSubmit_click);
tc1.Controls.Add(btnSubmit);
tr.Cells.Add(tc);
tr.Cells.Add(tc1);
tbldynamic.Rows.Add(tr);
pnlinfo.Controls.Add(tbldynamic);
Table tbl = new Table();
for (int i = 0; i < 5; i++)
{
TableCell tcell = new TableCell();
TableRow trow = new TableRow();
CheckBox _checkbox = new CheckBox();
_checkbox.ID = "chkDynamicCheckBox" + i;
_checkbox.Text = "Checkbox" + i;
tcell.Controls.Add(_checkbox);
trow.Cells.Add(tcell);
tbl.Rows.Add(trow);
}
pnlinfo.Controls.Add(tbl);
}
protected void btnSubmit_click(object sender, EventArgs e)
{
TextBox txtUserName = (TextBox)pnlinfo.FindControl("txtName");
TextBox txtEmail = (TextBox)pnlinfo.FindControl("txtEmail");
Response.Write("UserName: " + txtUserName.Text + "; " + "Email: " + txtEmail.Text);
}
build application and run in browser, finally you will get respected output
No comments:
Post a Comment