简体   繁体   中英

Cannot access my UI controls in C# code. What's wrong?

I cannot access my UI controls on my ASP.Net website.

When I create a brand new form and drag a control on it, I can use C# to change the properties of the control easily, like one would expect.

But when I try to do the same on another page, I cannot access any control whether I drag a new control on the page or not.

It seems the code behind and the visual page aren't connected.

How can I fix this?

off the top of my head:

Is the code behind file registered in the top line of the ASPX file?

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

Has the designer file been deleted, or otherwise corrupted? if so try deleting the deigner file. VS should regenerate it for you.

Check the build action on the designer/code behind files and make sure that they are both set to 'Compile' (you can change this setting by right-clicking on the files in VS and seleting properties, build action should be in the file properties editor)

Make sure your project file is set up correctly. sometimes going through a project file upgrade (like when you change VS versions) or simply sharing project files through a source contorl system can cause things to get out of whack. confirm that for your files you have entries that look like this in your csproj file (confirm with a text editor, notepad is fine):

<Compile Include="Page.aspx.cs">
  <DependentUpon>Page.aspx</DependentUpon>
  <SubType>ASPXCodeBehind</SubType>
</Compile>
<Compile Include="Page.aspx.designer.cs">
  <DependentUpon>Page.aspx</DependentUpon>
</Compile>

I hope one of these solves your problem!

I know this is an old question, but seeing as I have encountered the same issue when creating an aspx page without a designer file, I felt it was necessary to share my solution to the problem.

In order to use ASP controls present on a page, you need to do is declare the control as a field within the class, that is, the class associated with the 'Inherits' attribute in your page. For example, if I have a label control on my page with an ID of 'test', then I would declare the following in my class:

protected System.Web.UI.WebControls.Label test;

如果你没有designer.cs文件,只需右键单击aspx和“转换为Web应用程序”,然后你就会得到一个。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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