动态创建的复选框id没有找到
本文关键字:id 创建 复选框 动态 | 更新日期: 2023-09-27 18:10:24
我已经创建了一个面板,里面有一个表,然后我在里面动态地创建了复选框。
int RoleCount = CountRoles();
string[] RoleName = RoleNames();
CheckBox[] chk = new CheckBox[RoleCount];
Table TableCheckBox = new Table();
TablePanel.Controls.Add(TableCheckBox);
TableRow tRow = new TableRow();
for (int i = 0; i < RoleCount; i++)
{
chk[i] = new CheckBox();
chk[i].ID = "chk" + RoleName[i];
chk[i].Text = RoleName[i];
chk[i].ClientIDMode = System.Web.UI.ClientIDMode.Static;
TableCell tCell = new TableCell();
tCell.Controls.Add(chk[i]);
if (i != 0 && i % 3 == 0)
{
TableCheckBox.Rows.Add(tRow);
tRow = new TableRow();
}
if (i < RoleCount)
tRow.Cells.Add(tCell);
TableCheckBox.Rows.Add(tRow);
}
现在,如果我想通过代码找到这个控件,那么它不起作用。Cb返回null
int RoleCount = CountRoles();
string[] RoleName = RoleNames();
string chkboxbit = " ";
try
{
foreach (string s in RoleName)
{
for (int i = RoleCount-1; i >= 0; i--)
{
chkboxbit = "chk" + RoleName[i];
ContentPlaceHolder cph = (ContentPlaceHolder)this.Master.FindControl("ContentPlaceHolder1");
Panel panel = (Panel)cph.FindControl("TablePanel");
System.Web.UI.HtmlControls.HtmlTable table = (System.Web.UI.HtmlControls.HtmlTable)panel.FindControl("TableCheckBox");
System.Web.UI.HtmlControls.HtmlInputCheckBox cb = (System.Web.UI.HtmlControls.HtmlInputCheckBox)table.FindControl(chkboxbit);
if (cb != null)
cb.Checked= false;
}
}
}
catch
{
Response.Redirect("Error.aspx");
}
完成。因为我正在创建复选框类型,因此下面的代码是适合它的,我认为是因为我的代码运行正常。
ContentPlaceHolder cph = (ContentPlaceHolder)this.Master.FindControl("ContentPlaceHolder1");
Panel panel = (Panel)cph.FindControl("TablePanel");
System.Web.UI.HtmlControls.HtmlTable table = (System.Web.UI.HtmlControls.HtmlTable)panel.FindControl("TableCheckBox");
System.Web.UI.WebControls.CheckBox cb = (System.Web.UI.WebControls.CheckBox)table.FindControl(chkboxbit);
if (cb != null)
{
if (cb.Checked == true)
cb.Checked = false;
}