ASP.Net -> object does not exist in the current context – really??

Another one of those problems that can stump you for a while. I often make backups of files as I progress and sometimes leave them in the website folder, this was fine with classic ASP but as I have found with ASP.Net can cause all sorts of problems.One issue I was having was trying to reference a component in my aspx page from the codebehind page and seeing the following error when trying to reference a label control:

“Label2 does not exist in the current context”

So I found that the problem was even though I renamed one of my old files it still contained the class that my codebehind was referencing (i.e. the class names were still the same) – and therefore was not seeing the newly added Label control to my new code.Shame the compiler doesn’t realise the duplication and give some indication.

Lesson: Remove any backed up files from the web folder and/or build directory to avoid pain :)

Note:
From a comment made by Chris (below) this can also be caused by a missing files if it was built as a ‘Web Application’ project and you are now trying to build it as a ‘Web Site’ project (e.g. could be missing a designer.cs file).

Either when downloading source from another developer or migrating a web app from one server to another you may find it was actually created as a ‘Web Application’ project in Visual Studio, and if you have created it as a ‘Web Site’ project you may hit problems. The solution to this is to convert the project to a ‘Web Application’ (right click on your project in solution explorer) and then rebuild it.

  • Eagle

    can any one help me out . I am facing this kind of problem

    using System;

    using System.Collections.Generic;

    using System.Linq;

    using System.Web;

    using System.Web.UI;

    using System.Web.UI.WebControls;

    using System.Data.SqlClient;

    namespace AdoDemo

    {

    public partial class webformlast : System.Web.UI.Page

    {

    protected void Page_Load(object sender, EventArgs e)

    {

    String CS = “data source=.; database=sample; user id=sa; password=”;

    SqlConnection con= new SqlConnection(CS);

    SqlCommand cmd = new SqlCommand(“Select * from tblperson”, con);

    con.Open();

    GridView1.DataSource = cmd.ExecuteReader();

    GridView1.DataBind();

    con.Close();

    }

    }

    }

  • Deepak Srivastav

    Thanks a lot for this solution, it really saved my life.

  • Chris

    Your title was my exact thought when this error popped up. Sure enough, double-checking my project directory there was indeed a copy of the .aspx file. Pulling that out fixed it. Thanks so much!

  • Jon

    Thank you! It’s solution.

  • RaSor

    It did not solve my problem.

    I was porting aspx pages from a Web Site to a Web App project.
    After “converting to web app” the problem remained.
    One more thing missing was the default namespace that had to surround the code, too.
    The latter fixed it.

  • http://www.tangledwebgraphicsets.com/irenesmith/ irenesmith

    Thank God I found this post. I have been going crazy for two days. It never occurred to me that a renamed file would be included in the project if it didn’t show up in the solution explorer. As soon as I deleted the offending file, the project compiled and everything is working again.

    Which is lucky for me because I have a presentation tomorrow!

    • http://www.tpddesign.co.uk Simon

      Glad it helped and hope the presentation went well :)

    • jlbiggs

      Same for me, Irene. Very fortunate I found this topic and blog. I had created a second copy of an aspx form and its cs file, with different names than the original, in the same folder, and kept getting this message when building for any new control I added to the original form. Deleting the second set of files fixed the issue.

      John

  • Sean

    Bless you. That issue was bugging (no pun) the crap out of me for some time now. I had a backup of the page (no code behind) that was causing the naming conflict.

  • Anonymous

    thanks lot

  • http://eddiesblog.moviesbysmsblogs.com/ endurneweinty

    Truthful words, some authentic words dude. You made my day!

  • rose

    Hello, i’m having same problem, but cant solve it, dont have back up pages, or bad references on code behind.. what should i do?? plz help me

    • shibbard

      @Rose
      If that is the message you are getting then it is true.
      Either the codebehind page is not properly linked to the .aspx page, or you are referencing a control that is embedded in another control (in which case use .findcontrol(“”), or you are trying to reference it at a point in the page creation when it is not available (i.e. not all controls are accessible in page_load() – maybe try during the page databind or even the controls pre_render.

      Si.

  • Pooja

    Wow!! This sounds so simple.. But its an amazing tip.. Thank u!!

  • Amul

    Was really helpful…Keep up the good work..!!

  • Rupesh Bari

    Thanks a lot friend….its solve my problem please keep it up…

  • dan

    thanks shibbard! your suggestion also worked for me! =)

  • Raghav

    thanks its solve my problem please keep it up

  • http://uiuiu guytuytu

    uiui

  • Ravi

    Fantastic man, kudos to you! Solved a painful problem of ASP.NET and code-behind files.

  • Tim

    Helped me too! Thanks for posting your experience!

  • Kaye

    omg. chris! you saved my life!!!!!!!

    thanks for the commenter named chris.

  • Terry Schuld

    Thank you thank you.

  • Michael Daly

    That was my prob. Thanks for posting!

  • Anonymous

    Thanks to shibbard… This really helped!

  • Matt

    You are a godsend. Thank you.

  • Aaron Clint

    WOOT! Lifesaver thanks for the post and thanks to google for finding it !

  • Dave

    YES! thanks everyone — for me it was the ‘two pages referencing the same code-behind’

    UGH!

    asp classic was so much easier.

  • Daya

    Thank you so much… I was breaking my head for the last 2 days.. and ur suggestion worked for me…

  • http://www.fobiga.com Raju Visshwanath

    Thanks a lot. You saved me a day.

  • Soheil

    Hi , thank u very much . my problem is i have two class with the same name ..sorry for compiler that does not detect there two class with tha same name in two different file.

  • http://www.dsm-design.co.uk Chris

    Another possible solution, I downloaded source code from another developer which had been created as a web application however it did not include the designer.cs file. I then added the file to a website project. Eventual solution was to convert the project to a web application (right click on your project in solution explorer for those who dont know where to find it :)).

    • Jason

      This fixed my problem, thanks Chris.

      After migrating perfectly functioning web app from one development server to another, the designer controls would not be recognized. I tried most everything else in this thread until I came upon Chris’s solution.

      • shibbard

        A number of people have found this comment helpful.

        I have added it to the main post just in case its helpful to others. These sort of problems can have you stumped for days.

  • Thomas

    Thanks for the info. I had two pages referencing the same codebehind file. Just excluding one solved the problem.

  • Naren

    I was facing similar issues and stuck up

    Thanks to you. I excluded the backup files and it worked.

  • http://mp3bulet.com music

    What do you mean ?

  • jon

    Bless you- I worked for a while on this one too

  • Vishnu

    The above solution not solving my problem.. let me know wat goes worng here.. Plz its a quite urgent…

    MySqlConnection sConn = new MySqlConnection(System.Web.Configuration.WebConfigurationManager.ConnectionStrings[“mysql”].ConnectionString);
    protected void Page_Load(object sender, EventArgs e)
    {
    sConn.Open();
    MySqlDataAdapter da = new MySqlDataAdapter(“select appl_projInfoInvoiceNumber, appl_DateOfApplication, appl_DateInvoiced, appl_clientDetailsCompany, appl_projInfoProducedFor, appl_UserId, appl_type, appl_LicenseDetailsAmountText from sync_license_apps where appl_status = ‘invoiced'”, sConn);
    DataSet ds = new DataSet();
    da.Fill(ds, “sync_license_apps”);
    Gridview1.DataSource = da;
    GridView1.DataBind();
    sConn.Close();
    }

    thankss..

  • linsen

    I read one solution in the web “http://forums.asp.net/p/1006588/1736105.aspx”. This says to remove the build option, which i didn’t find satisfactory. But this was the correct solution(to remove any backup files, if any) :-)

  • shibbard

    lol

    glad it helped :)

  • Jacob

    YOU ARE THE SMARTEST PERSON IN THE WORLD

    I LOVE YOU

  • http://www.laksha.net Vinni

    Thanks so much. This helped.

  • Sridhar

    Thanks buddy…. It saved me lot of time!

  • Prashant Vedpathak

    Thank you,

    Simon Hibbard, I was tackling with this problem. I got some clue about this problem previously but u gave me the whole answer. Thank u very much. [:)]

  • Shaun

    I looked around the net ant it was cause i was referenceing the same code behind.

  • moe!

    ACTUALLY.. this ALMOST solved my problem.

    my actual problem was that I had more than 1 page inheriting from/pointing to the same code file.

    So in page2.aspx at the top, i had
    CodeFile=”page1.aspx.cs” Inherits=”page1″

    while really the top of page2.aspx should have had:
    CodeFile=”page2.aspx.cs” Inherits=”page2″

    this happened because i copy-pasted the code from page1.aspx into page2.aspx.

  • sa

    Thanks!!!!!!! saved me a lot of trouble

  • Markus

    Thanks, that pointed me to the problem.

  • metaldude

    I’ll give you $5 for saving my time!!!! (I know it’s worth more but that’s all I got at the moment :-))

    Thanks

  • Jay

    Thanks a million !!!!1

    I was working on these problem since last two long days…but your suggestion works…

    thank you very much.

    Regards,

    Jay Khanpara

  • http://pavithra.wordpress.com/ Pavithra

    I dont know why the code is not visible properly in my previous comment.Anyway,this is the line.

    Label lblname =
    (Label)formname.FindControl
    (“lblname”);

  • http://pavithra.wordpress.com/ Pavithra

    Even I faced the same problem.I added this line of code

    Label = (Label).FindControl(“”);

    This worked fine, as the label control is the child control of the Form.So label control is not accessible directly.

  • shibbard

    funny it seems to be more common than i thought – but certainly wasn’t easy for me to track down when i came accross it as i couldn’t find any reference to the problem elsewhere

    nice to see this has helped a few people out :)

  • Brian

    Helped me too! Here’s a twist on it. Another developer had copied an aspx page from another one and never changed the codebehind reference! So, adding controls to the original aspx and compiling resulted in an error in the .cs codebehind. However, it was not apparent the problem was that another aspx page was using the same codebehind.

  • iman

    Very thank you,

    i’ve been on the same situation without knowing how to solve the problem. You save my life dude.

  • Yasser Ahmed

    This error normally occurs when you are trying to access the value of a session variable such as Session[“UserID”] and you’re not doing that from a webform, usercontrol or a class that inherits from System.Web.UI.

    In this situation you can still access the session variable, but using a different path.
    For example to access a session variable named UserID you would normally use Session[“UserID”]; however, if the error The name ‘Session’ does not exist in the current context is returned, use the following path for retrieving the value of the session variable:

    HttpContext.Current.Session[“UserID”];

  • shibbard

    Hi Dan, I am glad this helped someone as it had me baffled for absolutely ages.

    I never did see this suggestion anywhere and thought if I could just get it up on the net somewhere it may just help someone else – which it seems it has and so it seems was worth while. Thanks for letting me know :>

  • Dan Bailiff

    THANK YOU!

    After reading through dozens of similar cries of help on the asp.net forums, I could not find a solution to this problem. But you described my situation exactly, so I excluded my backup copies of the file in question and it immediately compiled.

    THANK YOU!