asp.Net <control> does not exist in current context - c#

I am facing a problem: I have taken a dropdownList control and ID is
drpDownCountries in an ASP.NET project. The dropdownlist control is placed on page, in the code behind file of C#, while typing the control name drpDownCountries, this control ID is listed in object member list.
The code-behind code looks like this:
drpDownCountries.Attributes.Add("onBlur", "ErrorHighlight('" + drpDownCountries.ClientID + "','" + lblCountry.ClientID + "');");
But when I compile the project I am getting the following error:
Error: The name 'drpDownCountries' does not exist in the current context
I have checked this thing on different machines too, and the same error is occurring. I do not understand what the reason is or how to fix it.

Right-click on the ASPX (or ascx) file, and select Convert to web application (or something like that). That will force a refresh on the designer file.

I had this same problem and what worked for me was to make a change to the .ascx file in Design view and then save it. This finally forced Visual Studio to regenerate the designer.cs file and include my new control.

I have seen this error occur when there is a copy of the .aspx page in the project folder.
Example:
Error occurs in Test.aspx.
There is a Test-copy.aspx file in the project folder.
Delete, rename with a different extension, or move Test-copy.aspx to a different folder.
Error is resolved.

It's possible there is an error in your aspx/aspx file that is causing the designer file not to be updated correctly. You could confirm this by adding something new (eg. "") and see if you can access that. If not, something is probably broken in the markup that you'll need to fix.

So first check that your ascx document is defined like so
ExampleClass.ascx
<%# Control Language="C#" AutoEventWireup="true" CodeFile="ExampleClass.ascx.cs" Inherits="ExampleClass" %>
ExampleClass.ascx.cs
public partial class ExampleClass : System.Web.UI.UserControl
{
protected void Page_Load(object sender, System.EventArgs e)
{
}
}

In aspx this type of error often occurs when you miss runat="server"

Do not let Intellisense fool you. Sometimes (usually after fixing problems with duplicate class names), you simply need to rebuild the project and the reported errors go away. Reopening the file after the build might be necessary.

You should put some code to get help..
Anyway, the problem could be that drpDownCountries is contained within a Panel control.
The Panel control is a Container control, in that it can hold lots of
controls.
In order to access the controls within that Panel control,
you first need to "help" ASP.Net to find it.
The typical way of doing this is to use the FindControl method look here.
Code sample:
DropDownList myDrop = (DropDownList)this.Panel1.FindControl("drpDownCountries");
if(myDrop != null)
{
..somecode..
}

Recreate the project. Just create a new project and add the elements one by one and hope it won't happen again. If it does, well that's part of the Microsoft experience: recreate another project and so on, until you decide to quit your job and join open-source.
CORRECTION
I'm going to redo the project that I have been working on since the last 3 days using ASP .NET MVC. I should be using an open-source tech for sure, but too bad it's not my decision for this project to not use .NET.

If this is happening after copy/move pages to new location, or project, you may simply check if PageName.ascx.designer.cs is included in project.
There is a bug in visual studio (or maybe reshrper): It includes PageName.ascx and PageName.ascx.cs, but not PageName.ascx.designer.cs, which must be included manually.

The only thing that worked for me was to add a temp controller in the aspx file and saving it.
That generated the designer again, and my controllers are now recognized!
You can then remove the temp controller and save; it won't ruin anything.

Related

I have an error when I pull up a page from my web application but not my friend doesn't have that error when does

I am using Visual Studio 2015, using the ASP.NET framework and I'm having problems. I can't fix my error and would like some help.
Front End:
<asp:Button OnClick="imgBtnSortTickets_Click" ID="imgBtnSortTickets"
runat="server" Text="Sort" SkinID="Buttons" />
Code-behind:
protected void imgBtnSortTickets_Click(object sender, EventArgs e)
{}
I am working with source code and everything works fine until I add a button and add the onclick attribute. When I reference to my code behind the onclick will always get errors if it's to a new event click method. I even get this error when I reference to a javascript function. My friend however doesn't get this error when add new buttons. But when I try to run their code that they just added which worked on their end it won't work on mine. So basically If any new references are made to the code behind file using the onClick event I will receive an error even though I won't receive one on old ones? The following will be my error.
Compiler Error Message: CS1061: 'ASP.triptickets_aspx' does not contain a definition for 'imgBtnSortTickets_Click' and no extension method 'imgBtnSortTickets_Click' accepting a first argument of type 'ASP.triptickets_aspx' could be found (are you missing a using directive or an assembly reference?)
How can I fix this because neither myself or my friend know what's wrong since this exact button and event will work. I apologize if I didn't call something correctly because I'm an entry level developer.
It seems some of your autogenerated code got deleted somehow, and now your markup and your codebehind are out of sync.
You can fix this manually, but it's probably easier just to do it this way:
Edit the .aspx file in source code view and completely remove the markup for the button.
Access the .aspx page in designer view and add the button back by dragging a button from the toolkit.
Set the ID (and other properties) of the button using the Properties UI.
In the designer view, double click the button to autogenerate the scaffolding for the click event handler.
Edit the click event handler, being careful not to change its name or any part of its prototype.
If this fails, open your project in Visual Studio and do a global search of all files in the solution that contain "imgBtnSortTickets_Click". Based on the error, you should find some markup that references it. Whatever control is referencing it, delete the entire control, then recreate it using the designer. If you are unsure how to edit the markup directly, edit your post and paste the code so we can help you.

c# not recognizing html div element

best to show this by code example:
html
<div runat="server" id="PI"> </div>
c#
protected void addNewProject_Click(object sender, EventArgs e)
{
PI.attributes.add("z-index", "0");
}
basically gives me an error saying "the name PI does not exist int he current context."
Any idea why it says that?
Make sure that your .designer.* file has been updated with a variable for PI. Some source control systems lock the file and prevent Visual Studio from automatically updating the file.
If the variable hasn't been created for you, you can always go back to your .designer file and add the new variable yourself. Just follow the patter for your other ASP.NET controls.
You're looking for a partial class with the same name as your code behind class.
This SO question addresses your issue as well.
I found an alternative solution, instead of making the image switch z-indexes, I am making the asp.net panel switch z-indexes. For some reason when I try to declare my object in designer.cs file...it registers in code behind. This is good, however right when I test it out on a web-browser, the designer file auto-regenerates and gets rid of it again. So instead of playing around with the html controls I played around with what I know works and used the asp.net panel controls.
I always declare them in my codebehind file, something like this:
var myDiv = new HtmlGenericControl("div");
Then you just treat it the same as any other control on your page.

ASP/C# code behind can not reach control from markup

Issue:
I have a markup like this (only the important lines):
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="RTDeluxe.ascx.cs"
Inherits="MainSolution.CONTROLTEMPLATES.Kunde.RTDeluxe" %>
<ul id="linkUl" class="teaserLinksUL" runat="server"/>
The code-behind:
namespace MainSolution.CONTROLTEMPLATES.Kunde
public partial class RTDeluxe : UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
linkUl.InnerHtml = string.Empty;
}
}
I can access the ul inside the code-behind and get no compilation error. But, when I debug the code I get a NullReferenceException because linkUl is NULL.
First I thought that the namespaces are the reason. But, after several tries, I'm sure that they're correct. The FileLocation seems to be correct and the controltemplates folder of my iis has a "Kunde" folder with the corresponding ascx files in it.
I have other .ascx files with the same structure -> they're working like a charm.
Question:
Are there any other reasons than the namespace for such behaviour? Do you have any hints where I can look at?
Edit:
The RTDeluxe.ascx.designer.cs file exists, the generated linkUl looks like this:
protected global::System.Web.UI.HtmlControls.HtmlGenericControl linkUl;
Edit2:
Ok, I will try to answer all your questions. Thanks for your time and feedback!
I have restarted Visual Studio -> The Problem persists.
I also have cleaned up the solution and deployed a new one. -> The problem persists.
When I debug and check the control hierachy I can see that the label is NOT there.
When I change the ID the compiler throws an error in the code-behind (which is right). If i change the ID there two I get the same behavoiur as before.
I also restarted my IIS and the whole pc -> No changes.
I have added a Name attribute to the linkul-definition -> No changes.
When I try to use FindControl it returns NULL.
The target-framework is .NET 3.5
The linkul is NOT inside a repeater or any other controls.
Removing/changing the web.config does also not lead to a solution.
Adding EnsureChildControls before accessing the linkUl doesnt change anything.
Moving the code into Page_PreRender does also not work.
I will try out your suggestions not listed here and add them soon.
Edit3:
Here the full markup:
<%# Assembly Name="$SharePoint.Project.AssemblyFullName$" %>
<%# Assembly Name="Microsoft.Web.CommandUI, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="RTDeluxe.ascx.cs" Inherits="MainSolution.CONTROLTEMPLATES.Kunde.RTDeluxe" %>
<ul id="linkUl" class="teaserLinksUL" runat="server"/>
*Edit4:
Ok here some additional info I found out:
When I change something in the markup, like adding plain html text it's NOT recognized by or shown in the browser. When i do something like this:
Label label1 = new Label();
label1.Text = "hugo lives!";
Controls.Add(label1);
It is shown. It seems like in visual studio everything is fine... But "live" at the server the code-behind speaks to some weird different markup...
This might help You a bit:
On the code-behind file of the user-control at class level, add this code:
protected global::System.Web.UI.HtmlControls.HtmlGenericControl linkUl = new System.Web.UI.HtmlControls.HtmlGenericControl();
and remove the protected global::System.Web.UI.HtmlControls.HtmlGenericControl linkUl; from RTDeluxe.ascx.designer.cs file
It might be because its Object was just declared not created.
Hope this helps..
Have you tried calling EnsureChildControls before accessing the control or moving the code into OnPreRender?
Sometimes in situations such as this it may just be that Visual Studio has got into a bad state with regard to this file. I have found that deleting the files and recreating them will often resolve the issue. Make sure to copy the code somewhere so that you can paste it back into the newly created files.
Are you deploying using the visual studio publish functionality?
If so, try deleting the .ascx file on your destination server. I have had visual studio not recognize that the file has changed and then doesn't copy the new file over.
I've had a problem similar to this before in an .aspx file. It was caused by having optimizeCompilations set to true in my web.config file.
<system.web>
<compilation optimizeCompilations="true" />
</system.web>
When optimizeCompilations is set to true ASP.Net only rebuilds pages when it feels it is necessary. Sometimes it gets confused and doesn't realize you've made a change that needs a page rebuild resulting in a run-time error that the compiler doesn't catch. See here for more information about this setting http://msdn.microsoft.com/en-us/library/ms366723.aspx.
To fix the problem I had to temporarily set optimizeCompilations to false, rebuild my website, recycle my app pool, and then set it back to true again.
Hope this helps.

Controls in a telerik control not accessible from .cs file

I am trying to use this solution to access items inside a telerik menu item:
ascx code:
<asp:Label ID="DivLeave" runat="server"></asp:Label>
In the ascx.cs file I run this code to disable the asp label
RadMenuItem expenses = RadMenu1.FindItemByText("Expenses");
Label DivLeave = (Label)expenses.FindControl("DivLeave");
DivLeave.Visible = false;
but I get this error when I try to run the code:
{"Object reference not set to an instance of an object."}
Can anyone tell me how to fix this problem. I really need to run this server side as code surrounding the above code does some work server side and it will all fit in neatly...
Kind regards
This is because the name of your label is not "DivLeave" when the HTML for your form is rendered. Since it is inside a user control it will be a combination of the user control name on the page and then "DivLeave". You should be able to see the name by looking at the code behind. Also why can't you just reference DivLeave.Visible without using the FindControl? Its an ASP.NET control with the runat server attribute so it should be available to you.
Can you do a quickwatch for 'expenses' object in Visual Studio and see if 'DivLeave' is available? It may so happen that:
The label control is available but at a different level in the object.
The label control itself is not getting added to the parent 'expenses'.
Also, it would be a good idea to do a null check for expenses and DivLeave objects before accessing them.

Convert User Controls to Server Controls

I'm wondering if anyone has any experience converting User controls to Web controls?
Ideally, I'd like to offload some of the design work to others, who would give me nicely laid out User Controls. Then, I could go through the process of converting, compiling, testing and deploying.
Until MS comes up with the magic "Convert to Server Control" option, it looks like I'm pretty well stuck with re-writing from scratch. Any ideas?
Is there a reason you must convert these user controls to server controls? Remember that it is possible to compile a user control into an assembly.
You are right there is no magic bullet here but since you already have a User Control its not that difficult.
Make sure all properties, events, etc. are set in the code behind since you won't have any mark up when you're done
Create a new Server Control
Paste all of the event handling and property setting code into the new control
override the Render method for each child control call the RenderControl Method passing in the supplied HtmlTextWriter
protected override void Render(HtmlTextWriter writer)
{
TextBox box = new TextBox();
//Set all the properties here
box.RenderControl(writer);
base.Render(writer);
}
I searched for hours and found many blogs about it.
The only thing worked for me was this article https://blogs.msdn.microsoft.com/davidebb/2005/10/31/turning-an-ascx-user-control-into-a-redistributable-custom-control/.
It says self-contained with given restrictions, but it does not mentions that the codebehind must be included in ascx file.
I used a Web Site project (not Web application!) and had to inline the code behind into the ascx file and only use control directive like:
<%# Control Language="C#" ClassName="MyPackage.MyControl"%>
So basically i just have a single file left for the user control. When codebehind was a separate file all control's where null when i referenced the final dll.
I also tried http://blog.janjonas.net/2012-04-06/asp_net-howto-user-control-library-compile-dll-file but with reflection the ascx file could not be found.

Categories

Resources