我想动态生成文本框和下拉框作为html表列。像这样我想创建30行。如何在asp.net和c#.net中做到这一点?我想要在asp.net页面中做到这一点。
protected void Page_Load(object sender, EventArgs e)
{
TextBox txtbx= null;
DropDownList ddl = null;
for (int i = 0; i < 4; i++)
{
txtbx= new TextBox();
txtbx.ID = "mytxt" + i;
txtbx.Text = "mytxt" + i;
pnlButton.Controls.Add(txtbx);
ddl= new DropDownList();
ddl.ID = "mydropdown " + j;
ddl.Text = "mydropdown " + j;
ddl.Items.Add("Hii");
ddl.Items.Add("Hello");
ddl.AutoPostBack = true;
ddl.SelectedIndexChanged += new EventHandler(ddl_Click);
pnlButton.Controls.Add(ddl);
Literal lit = new Literal();
lit.Text = "</br></br>";
pnlButton.Controls.Add(lit);
}
}
On the aspx page use a panel for showing controls in a proper way like this and a button for saving data in
<asp:Panel ID="pnlQuestions" runat="server" Width="100%"> </asp:Panel> <asp:LinkButton ID="lbtnNext" runat="server" CssClass="button" ToolTip="Next" OnClick="lbtnNext_Click"><span>Save & Next</span></asp:LinkButton>
On the code behind aspx.cs page, you can generate all dynamic controls on Page_Init event
protected void Page_Init(object sender, EventArgs e) { TextBox txt = new TextBox(); txt.Text = QuestionText; txt.ID = "que1"; pnlQuestions.Controls.Add(txt); }
You can get all dynamic controls value on button click event like this
protected void lbtnNext_Click(object sender,EventArgs e) { TextBox txt = ((TextBox)pnlQuestions.FindControl("que1")); AnswerText = txt.Text.Trim(); Response.Write(AnswerText); }
By using this method you can generate and fetch dynamic controls on asp.net page.
for much more understanding : Check this link
To start off you would need something like
<asp:Table ID="mytbl" runat="server">
</asp:Table>
In the code behind then you can add as
TableRow trow;
TableCell tcell1, tcell2;
for (int i = 0; i < 30; i++)
{
trow = new TableRow();
tcell1 = new TableCell();
tcell1.Controls.Add(new TextBox());
tcell2 = new TableCell();
tcell2.Controls.Add(new DropDownList());
trow.Cells.Add(tcell1);
trow.Cells.Add(tcell2);
mytbl.Rows.Add(trow);
}
Add as you require details for ID, Name and dropdown items as you need
protected void Page_Load(object sender, EventArgs e)
{
TextBox box = new TextBox{ID="textbox1", Text="hello :)"};
form1.Controls.Add(box);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.