Asp.net controls are not accessible in code behind

后端 未结 26 1074
慢半拍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:01

    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.

    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).

    If you're working with a visual studio "project", then you can open the cs.designer file, and add your control. 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.

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

    Possible reasons:

    • id mismatch.
    • runat="server" not present in the control at .aspx file.

    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.

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

    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.

    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? 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". This got me going again after I ran into this problem.

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

    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.

    In previous versions of Visual Studio this wasn't an issue but it looks like VS2013 has tightened up.

    I hope this helps someone - I only spotted it thanks to Sergey's comment above.

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

    First

    • Make sure you assigned an ID to the control

    If this doesn't help

    • Close the page where you added the control
    • Rebuild/compile the project and open the page again
    0 讨论(0)
  • 2020-12-15 17:05

    manually enter declaration in other partial class

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