开发者

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

开发者 https://www.devze.com 2023-01-14 20:50 出处:网络
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 wou

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!


If you don't have a designer.cs file, just right-click on the aspx and "Convert to Web Application" and then you'll get one.


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;
0

精彩评论

暂无评论...
验证码 换一张
取 消