简体   繁体   English

Asp.net 控件无法在后面的代码中访问

[英]Asp.net controls are not accessible in code behind

I have a project that was previously built by someone else.我有一个以前由其他人构建的项目。 When I try to add a new control to the page, I can't access it in the code behind.当我尝试向页面添加新控件时,我无法在后面的代码中访问它。 When I try to access it there's an error message that the Control is not defined in the current context.当我尝试访问它时,会出现一条错误消息,指出控件未在当前上下文中定义。

<%@ Page Language="C#" MasterPageFile="~/HRMS.Master" AutoEventWireup="true"     CodeBehind="manageEmployee.aspx.cs" Inherits="HRMS.manageEmployee" Title="Untitled Page" %>

<%@ Register Assembly="eWorld.UI" Namespace="eWorld.UI" TagPrefix="ew" %>
<%@ Register assembly="AjaxControlToolkit" namespace="AjaxControlToolkit" tagprefix="cc1" %>


<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
    <script type="text/javascript">
    document.getElementById("employee").setAttribute("class", "selected");
    </script>
<!--OPEN CONTENT DIV-->

     <asp:ScriptManager ID="ScriptManager1" runat="server">
     </asp:ScriptManager>
    <!-- Only this area is updated on PostBack -->

<div class="manage_employ">

    <ul>
        <li style="margin-top:10px; margin-bottom:15px"><input type="image" src="images/img_manageEmployee01.png"/></li>
    </ul>

    <ul>
        <li>First name</li>
        <li><asp:TextBox runat="server" class="text_input" id="txtFirstName"/></li>
        <asp:RequiredFieldValidator ID="validatorFirstName" runat="server" ErrorMessage="*" ControlToValidate="txtFirstName"></asp:RequiredFieldValidator>
        <li>Last name</li>
        <li><asp:TextBox runat="server" class="text_input" id="txtLastName"/></li>
        <asp:RequiredFieldValidator ID="validatorLastname" runat="server" ErrorMessage="*" ControlToValidate="txtLastName"></asp:RequiredFieldValidator>
    </ul>

    <ul>
        <li>CNIC</li>
        <li><asp:TextBox runat="server" class="text_input" id="txtCNIC"/></li>
        <asp:RequiredFieldValidator ID="validatorCNIC" runat="server" ErrorMessage="*" ControlToValidate="txtCNIC"></asp:RequiredFieldValidator>
        <li>Blood Group</li>
        <li><asp:DropDownList runat="server" class="text_input" id="ddlBloodGroup">
        <asp:ListItem>A+</asp:ListItem>
        <asp:ListItem>B+</asp:ListItem>
        <asp:ListItem>AB+</asp:ListItem>
        <asp:ListItem>A-</asp:ListItem>
        <asp:ListItem>B-</asp:ListItem>
        <asp:ListItem>AB-</asp:ListItem>
        <asp:ListItem>O+</asp:ListItem>
        <asp:ListItem>O-</asp:ListItem>
        </asp:DropDownList>
        </li>
    </ul>

    <ul>
        <li>Mobile</li>
        <li><asp:TextBox runat="server" class="text_input" id="txtMobile"/></li>
        <asp:RequiredFieldValidator ID="validatorMobile" runat="server" ErrorMessage="*" ControlToValidate="txtMobile"></asp:RequiredFieldValidator>
        <li>Phone</li>
        <li><asp:TextBox runat="server" class="text_input" id="txtPhone"/></li>
    </ul>

    <ul>


    </ul>

    <ul>
        <li>E-Mail</li>
        <li><asp:TextBox runat="server" class="text_input" id="txtEmail"/></li>
        <asp:RegularExpressionValidator ID="valEmail" ControlToValidate="txtEmail" runat="server" ErrorMessage="*" ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*">*</asp:RegularExpressionValidator>
        <asp:UpdatePanel ID="UpdatePanel1" runat="server">
            <ContentTemplate>
            <li>Maritial Status</li>
            <li>
            <asp:RadioButton ID="rbtnMarried" AutoPostBack="true" runat="server" oncheckedchanged="rbtnMarried_CheckedChanged"/>Married
            <asp:RadioButton ID="rbtnUnmarried" AutoPostBack="true" runat="server" 
                    oncheckedchanged="rbtnUnmarried_CheckedChanged"/>Unmarried
            </li>
            </ContentTemplate>
        </asp:UpdatePanel>
    </ul>

    <ul>
        <li>Permanant Address</li>
        <li><asp:TextBox runat="server" class="text_input" id="txtPermanantAddress"/></li>
        <asp:RequiredFieldValidator ID="validatorPAddress" runat="server" ErrorMessage="*" ControlToValidate="txtPermanantAddress"></asp:RequiredFieldValidator>
        <li>Temporary Address</li>
        <li><asp:TextBox runat="server" class="text_input" id="txtTemporaryAddress"/></li>
        <asp:RequiredFieldValidator ID="validatorTAddress" runat="server" ErrorMessage="*" ControlToValidate="txtTemporaryAddress"></asp:RequiredFieldValidator>
    </ul>


    <ul>
        <li>Salary</li>
        <li><asp:TextBox runat="server" class="text_input" id="txtSalary"/></li>
        <asp:RequiredFieldValidator ID="validatorSalary" runat="server" ErrorMessage="*" ControlToValidate="txtSalary"></asp:RequiredFieldValidator>
        <li>Joining Date</li>

             <li>
        <%--<ew:calendarpopup ID="calJoiningDate" runat="server"></ew:calendarpopup>--%>
                  <asp:TextBox ID="CalJoiningDate1" runat="server" CssClass="text_input"></asp:TextBox>
                  <cc1:CalendarExtender ID="CalJoiningDate1_CalendarExtender" runat="server" 
                       Enabled="True" TargetControlID="CalJoiningDate1">
                  </cc1:CalendarExtender>
        </li>


    </ul>
    <ul>
        <li>Job Area</li>
        <li><asp:DropDownList runat="server" class="text_input" id="ddlJobArea"/></li>
        <li>Desigantion</li>
        <li><asp:DropDownList runat="server" class="text_input" id="ddlDesignation"/></li>
    </ul>

    <asp:UpdatePanel ID="updatePnl" runat="server">
    <ContentTemplate>    
    <div>
    <ul>
        <li style="margin-top:20px; margin-bottom:15px"><input type="image" src="images/img_jobHistory.png"  /></li>
    </ul>

    <ul>
    <li>Company</li>
   <%--<asp:DropDownList runat="server" class="text_input" id="ddlCompany" 
              onselectedindexchanged="ddlCompany_SelectedIndexChanged"/>--%>
          <li><asp:TextBox ID="CompanyNames" runat="server" CssClass="text_input"></asp:TextBox> 
               <cc1:AutoCompleteExtender ID="CompanyNames_AutoCompleteExtender" runat="server" 
                    DelimiterCharacters="" Enabled="True" ServicePath="getCompanies.asmx" ServiceMethod="getCompaniesMethod" MinimumPrefixLength="1" 
                    TargetControlID="CompanyNames" UseContextKey="True">
               </cc1:AutoCompleteExtender>
               <li>Job Duration</li>
               <li>
                    <asp:TextBox ID="txtJobDuration" runat="server" class="text_input" />
               </li>
               <asp:RequiredFieldValidator ID="validatorJobDuration" runat="server" 
                    ControlToValidate="txtJobDuration" ErrorMessage="*" 
                    ValidationGroup="jobHistory"></asp:RequiredFieldValidator>
         </li>
    </ul>

    <ul>
    <li>Job Area</li>
    <li><asp:DropDownList runat="server" class="text_input" id="ddlJobHistJobArea"/></li>
    <li>Designation</li>
    <li><asp:DropDownList runat="server" class="text_input" id="ddlJobHistoryDesignation"/></li>
    </ul>

    <ul>
    <li>Last Drawn Salary</li>
    <li><asp:TextBox runat="server" class="text_input" id="txtLastDrawnSalary"/>
         </li>
        <asp:RequiredFieldValidator ID="validatorLastDrawnSalary" runat="server" ValidationGroup="jobHistory" ErrorMessage="*" ControlToValidate="txtLastDrawnSalary"></asp:RequiredFieldValidator>
    </ul>

    <ul>
        <li style="margin-left:160px">
            <asp:ImageButton src="images/btn_Add.png" runat="server" ID="btnAddJobHistory" onclick="btnAddJobHistory_Click" CausesValidation="True" ValidationGroup="jobHistory"/>
            <asp:ImageButton src="images/btnReset.png" runat="server" ID="btnResetJH" CausesValidation="False" onclick="btnResetJH_Click"/>
        </li>
    </ul>

    <ul style="margin-left:30px">
    <asp:GridView ID="grdJobHistory" runat="server" AutoGenerateColumns="False" Width="798px" 
            AllowPaging="True" 
        onpageindexchanging="grdJobHistory_PageIndexChanging" 
        onrowcommand="grdJobHistory_RowCommand" 
            onrowdeleting="grdJobHistory_RowDeleting" 
            onrowediting="grdJobHistory_RowEditing" Font-Bold="True" 
            Font-Names="Calibri" Font-Size="Medium" ForeColor="White" PageSize="5">
            <Columns>
                <asp:BoundField DataField="EmployeeExperianceId" 
                    HeaderText="EmployeeExperianceId" />
                <asp:BoundField HeaderText="Company" DataField="CompanyName" ReadOnly="True" >
                    <ItemStyle Font-Names="Calibri,Verdana,Arial,Helvetica,sans-serif" 
                        Font-Size="Small" ForeColor="#3F4A53" />
                </asp:BoundField>
                <asp:BoundField DataField="JobAreaName" HeaderText="Job Area" >
                    <ItemStyle Font-Names="Calibri,Verdana,Arial,Helvetica,sans-serif" 
                        Font-Size="Smaller" ForeColor="#3F4A53" />
                </asp:BoundField>
                <asp:BoundField HeaderText="Designation" DataField="DesignationName" 
                    ReadOnly="True" >
                    <ItemStyle Font-Names="Calibri,Verdana,Arial,Helvetica,sans-serif" 
                        Font-Size="Small" ForeColor="#3F4A53" />
                </asp:BoundField>
                <asp:BoundField HeaderText="Experiance Duration" DataField="ExperianceDuration" 
                    ReadOnly="True" >
                    <ItemStyle Font-Names="Calibri,Verdana,Arial,Helvetica,sans-serif" 
                        Font-Size="Small" ForeColor="#3F4A53" />
                </asp:BoundField>
                <asp:BoundField HeaderText="Salary" DataField="LastDrawnSalary" ReadOnly="True" >
                    <ItemStyle Font-Names="Calibri,Verdana,Arial,Helvetica,sans-serif" 
                        Font-Size="Small" ForeColor="#3F4A53" />
                </asp:BoundField>
                <asp:TemplateField AccessibleHeaderText="Edit" HeaderText="Edit">
                    <ItemTemplate>
                        <asp:ImageButton ID="imgBtnEdit" runat="server" ImageUrl="images/updateIcon.png" CausesValidation="False" CommandName="Edit" CommandArgument='<%# DataBinder.Eval(Container.DataItem, "EmployeeExperianceId") %>'/>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField AccessibleHeaderText="Delete" HeaderText="Delete">
                    <ItemTemplate>
                        <asp:ImageButton ID="imgBtnDelete" runat="server" ImageUrl="images/deleteIcon.png" CausesValidation="False" CommandName="Delete" CommandArgument='<%# DataBinder.Eval(Container.DataItem, "EmployeeExperianceId") %>' OnClientClick="return confirm('Are you sure you want to delete this record...');"/>
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
            <HeaderStyle BackColor="#5D92B9" BorderStyle="None" />
            <AlternatingRowStyle BackColor="#AAAAAA" />
        </asp:GridView>
    </ul>

    </div>

    <div>
    <ul>
        <li style="margin-top:20px; margin-bottom:15px"><input type="image" src="images/img_skillDetail.png"  /></li>
    </ul>

    <ul>
        <li>Skill</li>
        <!--<li><asp:DropDownList runat="server" class="text_input" id="ddlSkill"/></li>-->
        <li>
             <asp:TextBox ID="SkillAutoComplete" runat="server" CssClass="text_input"></asp:TextBox>
             <cc1:AutoCompleteExtender ID="SkillAutoComplete_AutoCompleteExtender" 
                  runat="server" DelimiterCharacters="" Enabled="True" ServicePath="getSkills.asmx" ServiceMethod="getAllSkills" MinimumPrefixLength="1" 
                  TargetControlID="SkillAutoComplete">
             </cc1:AutoCompleteExtender>
         </li>
        <li>Skill Detail</li>
        <li><asp:TextBox runat="server" class="text_input" id="txtSkillDetail"/></li>
        <asp:RequiredFieldValidator ID="validatorSkillDetail" runat="server" ValidationGroup="skill" ErrorMessage="*" ControlToValidate="txtSkillDetail"></asp:RequiredFieldValidator>
    </ul>    

    <ul>
        <li style="margin-left:160px">
            <asp:ImageButton src="images/btn_Add.png" runat="server" ID="btnAddSkill" CausesValidation="True" ValidationGroup="skill" onclick="btnAddSkill_Click"/>
            <asp:ImageButton src="images/btnReset.png" runat="server" ID="btnResetSkill" CausesValidation="False" onclick="btnResetSkill_Click"/>
        </li>
    </ul>    

    <ul style="margin-left:30px">
    <asp:GridView ID="grdSkill" runat="server" AutoGenerateColumns="False" Width="798px" 
            AllowPaging="True" 
        onpageindexchanging="grdSkill_PageIndexChanging" 
        onrowcommand="grdSkill_RowCommand" 
            onrowdeleting="grdSkill_RowDeleting" 
            onrowediting="grdSkill_RowEditing" Font-Bold="True" 
            Font-Names="Calibri" Font-Size="Medium" ForeColor="White" PageSize="5">
            <Columns>
                <asp:BoundField HeaderText="EmployeeSkillId" DataField="EmployeeSkillId" >
                </asp:BoundField>
                <asp:BoundField DataField="SkillName" HeaderText="Skill Name" ReadOnly="True">
                    <ItemStyle Font-Names="Calibri,Verdana,Arial,Helvetica,sans-serif" 
                        Font-Size="Small" ForeColor="#3F4A53" />
                </asp:BoundField>
                <asp:BoundField HeaderText="Skill Detail" DataField="SkillDetail" 
                    ReadOnly="True" >
                    <ItemStyle Font-Names="Calibri,Verdana,Arial,Helvetica,sans-serif" 
                        Font-Size="Small" ForeColor="#3F4A53" />
                </asp:BoundField>
                <asp:TemplateField>
                    <ItemTemplate>
                        <asp:ImageButton ID="imgBtnEdit" runat="server" ImageUrl="images/updateIcon.png" CausesValidation="false" CommandName="Edit" CommandArgument='<%# DataBinder.Eval(Container.DataItem, "EmployeeSkillId") %>'/>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField>
                    <ItemTemplate>
                        <asp:ImageButton ID="imgBtnDelete" runat="server" ImageUrl="images/deleteIcon.png" CommandName="Delete" CommandArgument='<%# DataBinder.Eval(Container.DataItem, "EmployeeSkillId") %>' OnClientClick="return confirm('Are you sure you want to delete this record...');"/>
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
            <HeaderStyle BackColor="#5D92B9" BorderStyle="None" />
            <AlternatingRowStyle BackColor="#AAAAAA" />
        </asp:GridView>
    </ul>
    </div>

    <div>       
    <ul>
        <li style="margin-top:20px; margin-left:20px; margin-bottom:15px"><input type="image" src="images/img_qualificationDetail.png"  /></li>
    </ul>    

    <ul>
        <li>Course</li>
        <li><asp:DropDownList runat="server" class="text_input" id="ddlCourse"/></li>
        <li>Institution</li>
        <li><asp:TextBox runat="server" class="text_input" id="txtInstitution"/></li>
        <asp:RequiredFieldValidator ID="validatorInsitution" runat="server" ValidationGroup="course" ErrorMessage="*" ControlToValidate="txtInstitution"></asp:RequiredFieldValidator>
    </ul>        

    <ul>
        <li>Duration</li>
        <li><asp:TextBox runat="server" class="text_input" id="txtCourseDuration"/></li>
        <asp:RequiredFieldValidator ID="validatorDuration" runat="server" ValidationGroup="course" ErrorMessage="*" ControlToValidate="txtCourseDuration"></asp:RequiredFieldValidator>
        <li>Passing Year</li>
        <li>
             <asp:TextBox ID="calPassingYear1" runat="server" CssClass="text_input"></asp:TextBox>

        </li>
        <!--<li><ew:CalendarPopup ID="calPassingYear" runat="server"></ew:CalendarPopup></li>-->
    </ul>        

    <ul>
        <li>Marks/Percentage/GPA</li>
        <li><asp:TextBox runat="server" class="text_input" id="txtMarksPercentage"/></li>
        <asp:RequiredFieldValidator ID="validatorMarks" runat="server" ValidationGroup="course" ErrorMessage="*" ControlToValidate="txtMarksPercentage"></asp:RequiredFieldValidator>
        <li style="margin-left:160px">
        <asp:ImageButton src="images/btn_Add.png" runat="server" ID="btnAddCourse" CausesValidation="True" onclick="btnAddCourse_Click" ValidationGroup="course"/>
        <asp:ImageButton src="images/btnReset.png" runat="server" ID="btnResetCourse" CausesValidation="False" onclick="btnResetCourse_Click" />
        </li>
    </ul>        

    <ul style="margin-left:30px">
    <asp:GridView ID="grdCourse" runat="server" AutoGenerateColumns="False" Width="798px" 
            AllowPaging="True" 
        onpageindexchanging="grdCourse_PageIndexChanging" 
        onrowcommand="grdCourse_RowCommand" 
            onrowdeleting="grdCourse_RowDeleting" 
            onrowediting="grdCourse_RowEditing" Font-Bold="True" 
            Font-Names="Calibri" Font-Size="Medium" ForeColor="White" PageSize="5">
            <Columns>
                <asp:BoundField DataField="EmployeeQualificationId" 
                    HeaderText="EmployeeQualificationId" />
                <asp:BoundField HeaderText="Course" DataField="CourseTitle" ReadOnly="True" >
                    <ItemStyle Font-Names="Calibri,Verdana,Arial,Helvetica,sans-serif" 
                        Font-Size="Small" ForeColor="#3F4A53" />
                </asp:BoundField>
                <asp:BoundField HeaderText="Institution" DataField="InstitutionName" 
                    ReadOnly="True" >
                    <ItemStyle Font-Names="Calibri,Verdana,Arial,Helvetica,sans-serif" 
                        Font-Size="Small" ForeColor="#3F4A53" />
                </asp:BoundField>
                <asp:BoundField HeaderText="Duration" DataField="Duration" 
                    ReadOnly="True" >
                    <ItemStyle Font-Names="Calibri,Verdana,Arial,Helvetica,sans-serif" 
                        Font-Size="Small" ForeColor="#3F4A53" />
                </asp:BoundField>
                <asp:BoundField HeaderText="Passing Year" DataField="YearOfPassing" 
                    ReadOnly="True" >
                    <ItemStyle Font-Names="Calibri,Verdana,Arial,Helvetica,sans-serif" 
                        Font-Size="Small" ForeColor="#3F4A53" />
                </asp:BoundField>
                <asp:BoundField HeaderText="Marks/Percentage/GPA" DataField="MarksPercentage" 
                    ReadOnly="True" >
                    <ItemStyle Font-Names="Calibri,Verdana,Arial,Helvetica,sans-serif" 
                        Font-Size="Small" ForeColor="#3F4A53" />
                </asp:BoundField>
                <asp:TemplateField>
                    <ItemTemplate>
                        <asp:ImageButton ID="imgBtnEdit" runat="server" ImageUrl="images/updateIcon.png" CausesValidation="false" CommandName="Edit" CommandArgument='<%# DataBinder.Eval(Container.DataItem, "EmployeeQualificationId") %>'/>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField>
                    <ItemTemplate>
                        <asp:ImageButton ID="imgBtnDelete" runat="server" ImageUrl="images/deleteIcon.png" CommandName="Delete" CommandArgument='<%# DataBinder.Eval(Container.DataItem, "EmployeeQualificationId") %>' OnClientClick="return confirm('Are you sure you want to delete this record...');"/>
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
            <HeaderStyle BackColor="#5D92B9" BorderStyle="None" />
            <AlternatingRowStyle BackColor="#AAAAAA" />
        </asp:GridView>
    </ul>
    </div>
    </ContentTemplate>
      </asp:UpdatePanel>        
    <ul>
       <li style="margin-left:90px; margin-bottom:10px;">
       <asp:ImageButton ID="btnSubmit" AlternateText="submit button" runat="server" src="images/btn_Submit.png" onclick="btnSubmit_Click"/>
       </li>
    </ul>
</div>
            <!--CLOSE CONTENT DIV-->

</asp:Content>

For Example:例如:

When I was trying to add some ASP.NET server side controls like <asp:testBox id="txtBox" runat="server"/> they were not accessible in the code behind.:当我尝试添加一些 ASP.NET 服务器端控件时,例如<asp:testBox id="txtBox" runat="server"/>它们在后面的代码中无法访问:

Error: txtBox is not defined in the current Context...错误:txtBox 未在当前上下文中定义...

What am I doing wrong?我究竟做错了什么?

I had this problem when I moved a website into a main solution by creating an asp.net application project in the solution and copying aspx & aspx.cs files over.当我通过在解决方案中创建 asp.net 应用程序项目并复制 aspx 和 aspx.cs 文件将网站移动到主解决方案时,我遇到了这个问题。 I solved it by right clicking on the project and converting to a web application.我通过右键单击项目并转换为 web 应用程序来解决它。 This created the necessary designer.cs files which contain the code for the asp objects on the aspx page.这创建了必要的 Designer.cs 文件,其中包含 aspx 页面上的 asp 对象的代码。

This happens especially with older stuff in visual studio.这尤其发生在视觉工作室中的旧东西上。

In 1.1 (before "partial classes") you could always see the control declarations in the code-behind.在 1.1 中(在“部分类”之前),您总是可以在代码隐藏中看到控件声明。

In later versions, they moved that into a cs.designer file (so now you've got partial classes -- part in the.cs.designer file, and part in the.cs file).在以后的版本中,他们将它移到了一个 cs.designer 文件中(所以现在你有了部分类——一部分在 .cs.designer 文件中,一部分在 .cs 文件中)。

If you're working with a visual studio "project", then you can open the cs.designer file, and add your control.如果您使用的是视觉工作室“项目”,那么您可以打开 cs.designer 文件并添加您的控件。 Just look at how all of the other controls are declared -- that's all you have to do.看看所有其他控件是如何声明的——这就是你所要做的。

If you're working with a visual studio "website", then you're out of luck.如果您正在使用视觉工作室“网站”,那么您就不走运了。 There's no way to view or edit the cs.designer file, because it isn't there until the website is compiled.无法查看或编辑 cs.designer 文件,因为在网站编译之前它不存在。

Check to ensure the designer.cs file for the page is included in the project.检查以确保该页面的 Designer.cs 文件包含在项目中。 Right click it and see if you get the option to "Include in project."右键单击它,看看是否有“包含在项目中”的选项。

Just found this question, and I realise it's quite old, but I think I have a potential answer.刚刚发现这个问题,我意识到它已经很老了,但我想我有一个潜在的答案。 Your code-behind for the designer's partial class might not be included in the project - sometimes happens when you've renamed and/or copied the file.您的设计器部分 class 的代码隐藏可能不包含在项目中 - 有时会在您重命名和/或复制文件时发生。

Go to your page (let's call it Test.aspx) and expand its tree in the Solution Explorer - do you see a file called Test.aspx.cs and Test.aspx.designer.cs? Go 到您的页面(我们称之为 Test.aspx)并在解决方案资源管理器中展开其树 - 您是否看到名为 Test.aspx.csTest.aspx.designer.cs 的文件? If not, look for a button at the top of the Solution Explorer marked Show All Files.如果没有,请在解决方案资源管理器顶部查找标记为显示所有文件的按钮。 Click it - if you now see the.designer.cs file there, right-click it and select "include in project".单击它 - 如果您现在在那里看到 .designer.cs 文件,请右键单击它并 select “包含在项目中”。 This got me going again after I ran into this problem.在我遇到这个问题后,这让我再次开始。

if you are unable to find the control in.cs page, simply add the control reference in designer.cs page and try to access it again.如果您在.cs页面中找不到控件,只需在designer.cs页面中添加控件引用并尝试再次访问它。

I'm sure it will 100%.我相信它会100%。 this is what i learned这就是我学到的

Have you renamed your project file?你有没有重命名你的项目文件? If you have, then remember to rename the Inherits at the top of your ASPX page.如果有,请记住重命名 ASPX 页面顶部的继承。

If you're experiencing this issue in VS2013 in a Website (as opposed to a Web Application) and have more than one aspx file sharing a codebehind then you need to make sure that ALL the aspx files have exactly the same collection of controls.如果您在网站的 VS2013 中遇到此问题(而不是 Web 应用程序)并且有多个 aspx 文件共享代码隐藏,那么您需要确保所有 aspx 文件具有完全相同的控件集合。

In previous versions of Visual Studio this wasn't an issue but it looks like VS2013 has tightened up.在以前的 Visual Studio 版本中,这不是问题,但看起来 VS2013 已经收紧了。

I hope this helps someone - I only spotted it thanks to Sergey's comment above.我希望这对某人有所帮助-感谢上面谢尔盖的评论,我才发现它。

Use CodeBehind attribute instead of CodeFile attribute of Page tag.使用CodeBehind属性而不是 Page 标签的CodeFile属性。

Eg:例如:

 <%@ Control Language="C#" AutoEventWireup="true" **CodeBehind**="Results.ascx.cs" Inherits="MyApp.Results" %>

This happened to me in a website project in VS2010, but as I'm part of a larger team, I don't have the option to convert to Web Application as Domenic suggested.这发生在我在 VS2010 的一个网站项目中,但由于我是一个更大团队的一员,我无法按照 Domenic 的建议转换为 Web 应用程序。

It turns out it was because I had switched my default editor for ASPX files to "HTML Editor" instead of "Web Form Editor".原来这是因为我将 ASPX 文件的默认编辑器切换为“HTML 编辑器”而不是“Web 表单编辑器”。 I did this because intellisense was killing my computer whenever I opened an ASPX file.我这样做是因为每当我打开 ASPX 文件时,智能感知都会杀死我的计算机。 When I right clicked on this page to "Open With..." the "Web Form Editor", and added the controls again, it worked perfectly and they're now available in the code behind file.当我右键单击此页面以“打开方式...”“Web 表单编辑器”并再次添加控件时,它运行良好,它们现在可以在代码隐藏文件中使用。

Add an empty.aspx.designer.cs file to your project将 empty.aspx.designer.cs 文件添加到您的项目中

To have visual studio autocreate declarations of.aspx page controls you can add an empty YourWebPageName.aspx.designer.cs -file to your project.要让 Visual Studio 自动创建 .aspx 页面控件的声明,您可以将一个空的YourWebPageName.aspx.designer.cs -文件添加到您的项目中。

If added to the project externally you can add it to your project by right clicking the project, selecting new item and include the new.cs file into your project.如果从外部添加到项目中,您可以通过右键单击项目,选择新项目并将 new.cs 文件包含到您的项目中来将其添加到您的项目中。

Then, as soon as you make a minor modification to your YourWebPageName page in the design editor Visual Studio will populate your empty.cs file with declarations.然后,只要您在设计编辑器中对 YourWebPageName 页面进行小幅修改,Visual Studio 就会使用声明填充您的 empty.cs 文件。

First第一的

  • Make sure you assigned an ID to the control确保您为控件分配了一个 ID

If this doesn't help如果这没有帮助

  • Close the page where you added the control关闭添加控件的页面
  • Rebuild/compile the project and open the page again重建/编译项目并再次打开页面

Here are a list of troubleshooting I go through when I get similar problems.以下是我遇到类似问题时通过 go 进行的故障排除列表。

  1. Make sure the IDs you are tying to use in the code behind are actually declared in the markup确保您要在后面的代码中使用的 ID 实际在标记中声明
  2. Make sure these elements have 'runat="server"'确保这些元素具有 'runat="server"'
  3. If you are having problems with a specific control, try to create one near the top of the page, if that doesn't work either, it's a code generation problem如果您在使用特定控件时遇到问题,请尝试在页面顶部附近创建一个,如果这也不起作用,那就是代码生成问题

If 3. is your issue, temporarily remove the mark-up of the controls and any reference you had to them in the code behind, ie make it so you can successfully build.如果 3. 是您的问题,请暂时删除控件的标记以及您在后面的代码中对它们的任何引用,即制作它以便您可以成功构建。 Close the designer.cs file if you have it open and do a rebuild.如果您打开了 Designer.cs 文件并进行重建,请关闭它。 After which try to re-add a basic control (following step 1 and 2) and see if it shows up (it should).之后尝试重新添加一个基本控件(按照步骤 1 和 2)并查看它是否显示(应该)。 Then re-add your mark up as needed and you should find the code generation is working again.然后根据需要重新添加您的标记,您应该会发现代码生成再次正常工作。

I had the same issue when 2 ASP Pages were using the same Code Behind file (It was ASP.NET Web Site project in Visual Studio 2013, not an ASP.NET Web Application). I had the same issue when 2 ASP Pages were using the same Code Behind file (It was ASP.NET Web Site project in Visual Studio 2013, not an ASP.NET Web Application). I have solved the problem by changing it to use different Code Behind files for each page.我已经通过将其更改为对每个页面使用不同的代码隐藏文件来解决该问题。

Possible reasons:可能的原因:

  • id mismatch. id 不匹配。
  • runat="server" not present in the control at.aspx file.控件 at.aspx 文件中不存在 runat="server"。

The solution that I found, apart from correcting the above, is to rebuild the project:我找到的解决方案,除了纠正上述问题外,还重建项目:

One more thing you need to take care is, before rebuild, close the designer file.您需要注意的另一件事是,在重建之前,关闭设计器文件。

I had a similar problem.我有一个类似的问题。 I faced this problem when I tried to rename the aspx file.当我尝试重命名 aspx 文件时遇到了这个问题。 In my case, the class name was not updated from UpdateRecords to ModifyRecords when I renamed the aspx file to ModifyRecords.就我而言,当我将 aspx 文件重命名为 ModifyRecords 时,class 名称未从 UpdateRecords 更新为 ModifyRecords。 Hence none of the ASP.NET controls were accessible from the code behind.因此,无法从后面的代码访问 ASP.NET 控件。

Code behind before renaming:重命名前的代码:

public partial class UpdateRecords : System.Web.UI.Page

Code behind after renaming:重命名后的代码:

public partial class ModifyRecords : System.Web.UI.Page

If you try to rename aspx file or copy-paste from different file, just make sure, the class name is updated.如果您尝试重命名 aspx 文件或从其他文件复制粘贴,只需确保 class 名称已更新。

manually enter declaration in other partial class在其他部分 class 手动输入声明

I have the same problem.我也有同样的问题。 I found the solution by removing " PublicKeyToken=31bf3856ad364e35" Namespace="System.Web.UI" TagPrefix="asp" %> " from aspx page and it works normal now.我通过从 aspx 页面中删除“ PublicKeyToken=31bf3856ad364e35” Namespace="System.Web.UI" TagPrefix="asp" %> " 找到了解决方案,它现在可以正常工作了。

If your trying to access the tags from your own built in method on the back-end make sure that you don't make this method static - otherwise you wont have access to these tags...如果您尝试从后端自己的内置方法访问标签,请确保您没有使用此方法 static - 否则您将无法访问这些标签...

<p #id="myTag" runat="server">...</p>

private static void myMethod(){
    myTag.InnerText = "Hello" //You will not have access to this tag
}

private void myMethod(){
    myTag.InnerText = "Hello"; //You have access to tags
}

Faced a similar problem because the controls were either within the: "LoginView" or "AnonymousTemplate" and Viewstatemode was Disabled遇到了类似的问题,因为控件位于:“LoginView”或“AnonymousTemplate”中,并且 Viewstatemode 被禁用

Resolved by moving the Asp controls outside these tag elements通过将 Asp 控件移到这些标记元素之外来解决

I also had a similar problem in the past.我过去也遇到过类似的问题。 As you have mentioned that the project was previously built by someone else , So it must be coded in VB based coding and you can check that in web.config compilation details.正如您所提到的,该项目以前是由其他人构建的,因此必须使用基于 VB 的编码进行编码,您可以在 web.config 编译详细信息中查看。 Try copying the aspx page content onto your newly created C# aspx page and paste the code as well it will work.尝试将 aspx 页面内容复制到新创建的 C# aspx 页面并粘贴代码,它也可以工作。

Problem is you might have multiple aspx files with codefile in page directive points to same codebehind file.问题是您可能有多个 aspx 文件,其中页面指令中的 codefile 指向相同的代码隐藏文件。 It expects the same control to exists in all the aspx file linked to same code behind and thus throwing compilation error.它期望相同的控件存在于链接到相同代码的所有 aspx 文件中,从而引发编译错误。

If you still having the issue cleaning up the same as mentioned above, check the designer page and regenerate one.如果您仍然遇到与上述相同的问题,请检查设计器页面并重新生成一个。

protected global::System.Web.UI.WebControls.CheckBox CheckBoxName ;

Add your control id name to your designer.cs and then it will be available in your cs file.将您的控件 ID 名称添加到您的 Designer.cs,然后它将在您的 cs 文件中可用。

Very old question, but I ran into this issue today, and ended up figuring out a solution that I didn't see mentioned here.非常老的问题,但我今天遇到了这个问题,最终找到了一个我在这里没有提到的解决方案。 So, I'll share it.所以,我来分享一下。

There are three files in a page: the ASPX, the ASPX.CS, and the ASPX.Designer.CS一个页面中有三个文件:ASPX、ASPX.CS 和 ASPX.Designer.CS

When you edit the HTML/Markup for the ASPX directly (like I prefer to do), it doesn't automatically update the designer.当您直接编辑 ASPX 的 HTML/标记时(就像我喜欢做的那样),它不会自动更新设计器。 That's why it's not showing up in intellisense (at least for me).这就是为什么它没有出现在智能感知中(至少对我而言)。 To get the IDE to update the designer, you have the ASPX page open in Visual Studio (and have it be the focused file);要让 IDE 更新设计器,您需要在 Visual Studio 中打开 ASPX 页面(并让它成为焦点文件); click on the "view" menu, and select "designer" (or hit Shift+F7);单击“查看”菜单,然后单击 select“设计器”(或按 Shift+F7); the IDE will show you the design view; IDE 将向您展示设计视图; right-click in the design area and select "refresh" from the context menu;右键单击设计区域并从上下文菜单中“刷新”select; save the file;保存文件; select "markup" from the "view" menu (or hit Shift+F7 again); select “查看”菜单中的“标记”(或再次按 Shift+F7); and check the designer file to see if the controls you added now exist in the designer.并检查设计器文件以查看您添加的控件现在是否存在于设计器中。

There might be a simpler way, but this worked for me to be able to access a control from the code behind that I had added to the HTML manually.可能有一种更简单的方法,但这对我来说能够从我手动添加到 HTML 的代码中访问控件。

I solved this problem by forcing the VS to regenerate my designer file.我通过强制 VS 重新生成我的设计器文件解决了这个问题。 For that:为了那个原因:

  1. I deleted my designer.cs file.我删除了我的 Designer.cs 文件。
  2. Copied the designer file of another page.复制了另一个页面的设计器文件。
  3. Renamed the designer file and the partial class in it to match the name of my page code behind class.重命名设计器文件和其中的部分 class 以匹配我在 class 后面的页面代码的名称。
  4. Deleted everything from the designer class body.删除了设计师 class 身上的所有内容。
  5. Cut all the controls from the aspx markup page.从 aspx 标记页面中剪切所有控件。
  6. Saved the aspx page.保存了aspx页面。
  7. Pasted the controls back and saved the file again.将控件粘贴回来并再次保存文件。

This made VS recreate all the controls in the blank designer file.这使得 VS 重新创建了空白设计器文件中的所有控件。

Hope that works for you.希望这对你有用。

Make sure your control should have a generated code-behind reference at all, For example.确保你的控件应该有一个生成的代码隐藏引用,例如。 if it's in a list template then you'll need to look up a reference to it in an item binding event handler.如果它在列表模板中,那么您需要在项目绑定事件处理程序中查找对它的引用。

This drove me wild because I had two controls with the same ID, one was at page level whereas the other was in a template.这让我抓狂,因为我有两个具有相同 ID 的控件,一个在页面级别,另一个在模板中。

I thought the generated reference I was using was for the one in the template and I couldn't work out why a newly added control in the template wasn't resulting in a generated reference.我认为我使用的生成引用是模板中的引用,我无法弄清楚为什么模板中新添加的控件没有生成生成引用。

Make sure the codeBehind attribute in page directive refer to the cs file where you call the control确保 page 指令中的 codeBehind 属性引用您调用控件的 cs 文件

So old question, But if it helps try to move controls outside any other control because accessing make different.这么老的问题,但是如果它有助于尝试将控件移到任何其他控件之外,因为访问会有所不同。

This is an old one but I ran into the same issue today and after bumping my head here and there, I found out that controls you add in GridViews are generated dynamically so, you need to access them based on the index they are present at (Just like lists/arrays in regular programming) instead of IDs.这是一个旧问题,但我今天遇到了同样的问题,在到处碰头之后,我发现你在 GridViews 中添加的控件是动态生成的,所以你需要根据它们所在的索引来访问它们(就像常规编程中的列表/数组一样)而不是 ID。

Hence, if you're adding your new controls in GridView, you will need to access them via indexes.因此,如果您在 GridView 中添加新控件,则需要通过索引访问它们。 A good practice would be to create ENUM in code behind for the GridView items indexes.一个好的做法是在 GridView 项目索引的代码中创建 ENUM。

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

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