简体   繁体   English

FindControl找不到控件

[英]FindControl can't find a control

I have a problem with FindControl function. 我对FindControl函数有问题。 The problem is as follow: 问题如下:

aspx: ASPX:

<asp:Content ID="MainContent" ContentPlaceHolderID="MainContent" runat="server">
  <ajaxToolkit:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server">
  </ajaxToolkit:ToolkitScriptManager>

  <table class="inputTable">
            <tr><td>
                <asp:CheckBox ID="Extern" AutoPostBack="True" OnCheckedChanged="OnCheckedChangedMethod" runat="server" />
                </td><td>Externes Unternehmen</td></tr>
    <tr>         
        <td>
            <asp:TextBox ID="Firmierung" runat="server"></asp:TextBox>
            <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" 
                ControlToValidate="Firmierung" Display="Dynamic" 
                ErrorMessage="RequiredFieldValidator"
                Text="Bitte geben Sie die Firmierung ein."></asp:RequiredFieldValidator>                
        </td>
    </tr>
  </table>  

aspx.cs: aspx.cs:

protected void OnCheckedChangedMethod(object sender, EventArgs e)
    {            
        if (Extern.Checked)
        {                
            Control ctr = FindControl("RequiredFieldValidator1");                
            if (ctr != null)
            {
                ctr.Visible = false;
            }
        }
        else
        {                
        }
    }

But FindControl didn't work, it couldn't find that control. 但是FindControl不起作用,它找不到该控件。 Was I wrong at any point? 我在任何时候都错了吗? Thanks in advance. 提前致谢。

ASP.NET creates a field for you, as it is located inside a Content : this.RequiredFieldValidator1 in your page. ASP.NET为您创建一个字段,因为它位于页面中的Contentthis.RequiredFieldValidator1

The FindControl way would be like this (find it in the master page's content panel): FindControl方式将是这样的(在母版页的内容面板中找到它):

Control ctr = Master.FindControl("MainContent")
    .FindControl("RequiredFieldValidator1");

Based on your limited source, you should be able to simplify your code behind method to: 根据有限的来源,您应该可以将方法的代码简化为:

protected void OnCheckedChangedMethod(object sender, EventArgs e)
{            
    this.RequiredFieldValidator1.Visible = this.Extern.Checked;
}

There should be no need for the use of FindControl(). 不需要使用FindControl()。

When you type "this.", if you don't see RequiredFieldValidator1 appear in your intellisense, and assuming you are using ASP.NET 2.0 or greater, check your VS.NET warnings to see if your .aspx has a warning message with an associated "Generation of designer file failed". 当您键入“ this。”时,如果您没有在智能感知中看到“ RequiredFieldValidator1”,并且假设您使用的是ASP.NET 2.0或更高版本,请检查VS.NET警告,以查看您的.aspx是否带有警告消息并带有关联的“设计器文件生成失败”。 If so, you must correct the warning. 如果是这样,则必须更正警告。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM