我创建了一个网页,我曾经动态地将服务器端控件添加到表中。
我分别为它们分配了 id。但我无法访问这些动态创建的服务器控件。
C#代码:
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
int num_row = (int)Session["No_of_Rows"];
for (int i = 2; i < num_row; i++)
{
TableRow row = new TableRow();
TableCell cell1 = new TableCell();
TableCell cell2 = new TableCell();
TextBox tb = new TextBox();
CheckBox cb = new CheckBox();
row.ID = "rw" + i;
cell1.ID = "c" + i + "1";
cell2.ID = "c" + i + "2";
tb.ID = "txt" + i;
tb.EnableViewState = true;
cb.ID = "chk" + i;
cell1.Controls.Add(cb);
cell2.Controls.Add(tb);
row.Cells.Add(cell1);
row.Cells.Add(cell2);
tbl.Rows.Add(row);
}
}
else
{
Session["No_of_Rows"] = 2;
}
}
protected void addRow(object sender, EventArgs e)
{
int num_row = (int)Session["No_of_Rows"] + 1;
TableRow row = new TableRow();
TableCell cell1 = new TableCell();
TableCell cell2 = new TableCell();
TextBox tb = new TextBox();
CheckBox cb = new CheckBox();
row.ID = "rw" + num_row;
cell1.ID = "c" + num_row + "1";
cell2.ID = "c" + num_row + "2";
tb.ID = "txt" + num_row;
//tb.EnableViewState = true;
cb.ID = "chk" + num_row;
cell1.Controls.Add(cb);
cell2.Controls.Add(tb);
row.Cells.Add(cell1);
row.Cells.Add(cell2);
tbl.Rows.Add(row);
Session["No_of_Rows"] = tbl.Rows.Count;
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
TextBox tb = new TextBox();
int num_row = Convert.ToInt16(tbl.Rows.Count);
for (int i = 1; i < num_row; i++)
{
string tstr = "txt" + i;
tb = (TextBox)this.FindControl(tstr);
}
Label1.Text = tb.Text;
}
ASP代码:
<form id="form1" runat="server">
<div>
<asp:Label ID="Label1" runat="server" Text="textbox value is"></asp:Label>
<asp:Table ID="tbl" runat="server">
<asp:TableRow ID="rw0">
<asp:TableCell ID="c01" Width="100px">
<asp:CheckBox runat="server" ID="chk0" />
</asp:TableCell>
<asp:TableCell ID="c02" Width="100px">
<asp:TextBox runat="server" ID="txt0" />
</asp:TableCell></asp:TableRow>
<asp:TableRow ID="rw1">
<asp:TableCell ID="c11" Width="100px">
<asp:CheckBox ID="chk1" runat="server" />
</asp:TableCell>
<asp:TableCell ID="c12" Width="100px">
<asp:TextBox runat="server" ID="txt1" />
</asp:TableCell></asp:TableRow>
</asp:Table>
<asp:Button ID="btn1" runat="server" Text="Add Row" OnClick="addRow" />
</div>
<asp:Button ID="btnSubmit" runat="server" OnClick="btnSubmit_Click" Text="Submit" />
</form>
请在这方面帮助我。