Asp.net controls are not accessible in code behind

后端 未结 26 1077
慢半拍i
慢半拍i 2020-12-15 16:25

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

相关标签:
26条回答
  • 2020-12-15 17:06
    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.

    0 讨论(0)
  • 2020-12-15 17:07

    Use CodeBehind attribute instead of CodeFile attribute of Page tag.

    Eg:

     <%@ Control Language="C#" AutoEventWireup="true" **CodeBehind**="Results.ascx.cs" Inherits="MyApp.Results" %>
    
    0 讨论(0)
  • 2020-12-15 17:08

    Add an empty .aspx.designer.cs file to your project

    To have visual studio autocreate declarations of .aspx page controls you can add an empty YourWebPageName.aspx.designer.cs -file to your project.

    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.

    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.

    0 讨论(0)
  • 2020-12-15 17:11

    I solved this problem by forcing the VS to regenerate my designer file. For that :

    1. I deleted my designer.cs file.
    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.
    4. Deleted everything from the designer class body.
    5. Cut all the controls from the aspx markup page.
    6. Saved the aspx page.
    7. Pasted the controls back and saved the file again.

    This made VS recreate all the controls in the blank designer file.

    Hope that works for you.

    0 讨论(0)
  • 2020-12-15 17:13

    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.

    I'm sure it will 100%. this is what i learned

    0 讨论(0)
  • 2020-12-15 17:13

    I had a similar problem. I faced this problem when I tried to rename the aspx file. In my case, the class name was not updated from UpdateRecords to ModifyRecords when I renamed the aspx file to ModifyRecords. Hence none of the ASP.NET controls were accessible from the code behind.

    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.

    0 讨论(0)
提交回复
热议问题