c# - 在后面的代码中引用非 asp 复选框
问题描述
我试图在后面的 C# 代码中引用一个非 asp 复选框。复选框不是 asp 元素的原因是它是动态自动生成的,而不是网站的一部分。到目前为止,我有以下相关的 aspx:
<asp:Table ID="myTable" runat="server" Width="100%">
<asp:TableRow>
<asp:TableCell>A</asp:TableCell>
<asp:TableCell>B</asp:TableCell>
<asp:TableCell>C</asp:TableCell>
<asp:TableCell>D</asp:TableCell>
<asp:TableCell>E</asp:TableCell>
</asp:TableRow>
</asp:Table>
<asp:LinkButton runat="server" ID="TEST" CssClass="btn btn-default pull-right" OnClick="TEST_Click">
TEST <i class="m-icon-swapright m-icon-white"></i>
</asp:LinkButton>
后面的C#代码是:
public void GenerateTable()
{
int i = 0;
bool[] box = {true, false, true, false, true};
List<TableRow> tRows = new List<TableRow>();
TableRow newRow = new TableRow();
tRows.Add(newRow);
foreach (var check in box)
{
TableCell tempCell = new TableCell();
if (check)
{
tempCell.Text = "<input type=\"checkbox\" id=\"chk" + i + "\" >";
}
else
{
tempCell.Text = "<input type=\"checkbox\" id=\"chk" + i + "\" checked>";
}
tRows[0].Cells.Add(tempCell);
i++;
}
foreach (TableRow row in tRows)
{
myTable.Rows.Add(row);
}
}
public void TEST_Click(object sender, EventArgs e)
{
HtmlInputCheckBox chkbox = (HtmlInputCheckBox)FindControl("chk1");
if (chkbox != null)
{
if (!chkbox.Checked)
{
MessageBox.Show("Checked");
}
else
{
MessageBox.Show("NOT Checked");
}
}
else
MessageBox.Show("NOTHING :(");
}
chkbox 始终为空 :(。
解决方案
你需要改变两件事。
为了通过FindControl
它找到一个复选框,它必须是页面控件集合的一部分,这意味着您必须添加一个CheckBox
控件。
CheckBox c = new CheckBox { ID = "chk" + i };
tempCell.Controls.Add(c);
动态添加CheckBox
的控件是 的控件集合的一部分Table
,因此您必须在那里而不是在页面上搜索它。
CheckBox chkbox = (CheckBox)this.myTable.FindControl("chk1");
您可以在下面找到代码的完整更新。
protected void Page_Load(object sender, EventArgs e)
{
GenerateTable();
}
public void GenerateTable()
{
int i = 0;
bool[] box = {true, false, true, false, true};
List<TableRow> tRows = new List<TableRow>();
TableRow newRow = new TableRow();
tRows.Add(newRow);
foreach (var check in box)
{
TableCell tempCell = new TableCell();
CheckBox c = new CheckBox { ID = "chk" + i };
c.Checked = check;
tempCell.Controls.Add(c);
tRows[0].Cells.Add(tempCell);
i++;
}
foreach (TableRow row in tRows)
{
myTable.Rows.Add(row);
}
}
public void TEST_Click(object sender, EventArgs e)
{
CheckBox chkbox = (CheckBox)this.myTable.FindControl("chk1");
if (chkbox != null)
{
if (!chkbox.Checked)
{
MessageBox.Show("Checked");
}
else
{
MessageBox.Show("NOT Checked");
}
}
else
{
MessageBox.Show("NOTHING :(");
}
}
推荐阅读
- excel - 防止饼图中数据标签重叠
- caching - 如何使用 perf 定期采样缓存未命中率?
- azure - Azure B2C - 无需创建用户即可启用登录
- mongodb - 无法从 MongoDB 或 DocumentDB 查询归档集合
- flutter - 可忽略的内容
- reactjs - 嵌套链接和活动类名不起作用
- python-3.x - 在python中构建字节
- flutter - 垂直包裹在 Scrollbar Widget 中的 PageView 小部件
- python - 我什至如何在 Python 中使用“else”语法?
- linux-device-driver - 如何为 Beaglebone 的 SPI 接口添加对超过 4 个片选的支持