0

我无法使用 FindControl 方法在我的 asp Web 应用程序上找到 asp:checkbox。我使用以下方法在表单上放置了一个复选框:

<asp:CheckBox ID="test" Text="Test checkbox" runat="server" />

在我的代码隐藏中,我有以下内容:

Control checkbox = FindControl("test");
if (checkbox != null) Debug.Print("checkbox found");
else Debug.Print("checkbox not found");

if (test.Checked) Debug.Print("checkbox is checked");
else Debug.Print("checkbox is unchecked");

但是我的输出(选中复选框)是:未找到复选框复选框已选中

有人可以告诉我我做错了什么吗?

4

2 回答 2

4

FindControl方法不是递归的,只有在复选框的直接父级上调用它时才会找到您的控件。因此,例如,如果复选框被放置在一个UpdatePanel也在页面内的内部;你需要调用FindControlUpdatePanel不是Page.FindControl像你正在做的那样。

您的输出显示的原因是:checkbox not found checkbox is checked是因为您test.checked直接调用,这将始终有效,因为这是您为复选框提供的 ID。

同样,FindControl它不是递归的,我很肯定这就是它失败的原因。您可以编写自己的“RecursiveFindControl”方法,但这几乎总是矫枉过正且效率低下。

于 2012-07-19T17:08:56.447 回答
0

您可以使用递归方法通过以下方式找到控件:

private Control RecursiveFindControl(Control root, string id)
{
    if (root.ID == id) return root;
    foreach (Control c in root.Controls)
    {
        Control t = RecursiveFindControl(c, id);
        if (t != null) return t;
    }
    return null;
}

使用上面的递归方法找到控件:

CheckBox checkbox =  RecursiveFindControl(Page, "test") as CheckBox;
if (checkbox != null) Debug.Print("checkbox found");
else Debug.Print("checkbox not found");

if (test.Checked) Debug.Print("checkbox is checked");
else Debug.Print("checkbox is unchecked");
于 2012-07-19T17:09:51.293 回答