Can't access control ID in code behind

2019-01-14 12:01发布

I have the following code in my aspx page:

 <asp:Button runat="server" ID="myButton" Text="hello" />

and this in my code behind:

protected void Page_Load(object sender, EventArgs e)
{ 
    myButton.Text = "bye"; 
}

For some reason the intellisense picks up the "myButton" id in the code behind but when it compiles it says

it can't build because it doesn't recognise it!

My page is a default aspx page which uses a master page, the button is inside a content control and all is set to run at server correctly, the page runs and displays fine except for this button resolution issue!

Any ideas?

13条回答
唯我独甜
2楼-- · 2019-01-14 12:25

Sounds like your designer file (PageName.designer.cs) has got a bit messed up. I'd try deleting the button from your page and adding it again.

查看更多
Melony?
3楼-- · 2019-01-14 12:25

I had the same problem today and in my case the solution was:

  • Go to: C:\Users\lenovo\AppData\Local\Temp\Temporary ASP.NET Files\
  • Delete the Temporary ASP.NET Files folder.
查看更多
Animai°情兽
4楼-- · 2019-01-14 12:27

Check the namespace in all three files. Sometimes there is a discrepancy between the namespace name in the designer.cs file and the other two files. Be sure to check that name space name match in all three files

查看更多
爱情/是我丢掉的垃圾
5楼-- · 2019-01-14 12:29

i know that problem is solved, but when i had a similiar problem, when i have convert WebAplication From c# to VB - i solved this by adding Namespace X / End Namespace

查看更多
放荡不羁爱自由
6楼-- · 2019-01-14 12:30

Problem is you might have multiple aspx files with codefile in page directive points to same codebehind file. It expects the same control to exists in all the aspx file linked to same code behind and thus throwing compilation error.

查看更多
放荡不羁爱自由
7楼-- · 2019-01-14 12:33

Just change the inherit property under page tag

    <% Page inherit = "Project_Name.otherform" 

change it to

    <% Page inherit = "Project_Name.YourForm"

And you will see in form2.aspx.desginer.cs the class name is also changed and corrected.

Let Me Explain: Let's Say you have 2 web forms test1.aspx and test2.aspx. You copied some piece of code from test1.aspx to test2.aspx, your test2.aspx file will use <% page tag as:

    <% Page inherit = "Project_Name.test1"

which was supposed to be as:

    <% Page inherit = "Project_Name.test2"

because of which your test2.aspx.designer.cs class name will be automatically changed to same as test1.aspx.designer.cs as it is a system generated file and you will be unable to use your control IDs.

After correcting your inherit property, save and Open test2.aspx.designer.cs to verify and you will see in that the class name is also changed. it will be like:

    public partial class test1
    {
     ...

Changed in to

    public partial class test2
    {
    ... 

Thanks me later ;)

查看更多
登录 后发表回答