swydell
swydell

Reputation: 2022

label1 doesn't exist in current context:asp.net C#

I have a project in which I create 2 int variables m = 5 and s =2 and assign datetime objects minutes to m and seconds to s. Then concatenate each to a string var str and perform increments of + and - and * to obtain new values. This is actually my first project in asp.net and I'm using C# language that I'm learning as I practice. I don't quite understand this label1 doesn't exist in current context. I followed the examples in my learning tutors exactly. In this forum I found solution that's beyond my beginner scope and knowledge. But I would appreciate it if someone could point me in the right direction. I've been going in circles since yesterday. Thank you in advance. Here is the code.

  <%@ Page Language="C#" %>
  <script runat="server">
  void Page_Load()
  {
  String str = "";
  int m, s;
  m = 5;
  s = 2;
  label1.Text = str; 
 m = 5;
 s = 2;
 str += "m+s" + (m+s) + "<br/>";
 label2.Text = str;
 m = 5;
 s = 2;
 str += "m-s" + (m-s) + "<br/>";
 label3.Text = str;
 m = 5;
 s = 2;
 str += "m*s" + (m*s) + "<br/>";
 label4.Text = str;
 }

 </script>
<!Doctype html>
 <html>
 <body>
 <%--
 Heading
 Student: Schweidel Tyson;
 'File name: ex02.aspx
 --%>
 m = <%=DateTime.Now.Minute%><br>
 s = <%=DateTime.Now.Second%>
  <asp:Label id="Label1" runat="server"/></asp:Label>
 m+s = <%=str%>
 <asp:Label id="Label2" runat="server"/></asp:Label> 
 m-s = <%=str%>
 <asp:Label id="Label3" runat="server"/></asp:Label> 
m*s = <%=str%>
<asp:Label id="Label4" runat="server"/></asp:Label> 
 </body>
 </html>

Upvotes: 0

Views: 736

Answers (2)

levelonehuman
levelonehuman

Reputation: 1505

In your page, you're creating a label with an id of Label1. Then in your code-behind, you're referring to it as label1 (note the difference in case).

The issue here is that Label1 != label1. Change either the declaration or the code so these match, and you should no longer have this error.

As an additional note, you should really consider using better variable names, like labelText, minutes, seconds, etc. In my opinion this code is difficult to read, and formatted code with good names is much easier to troubleshoot.

Upvotes: 2

Huuqwas
Huuqwas

Reputation: 1

Doesn't exist in current context usually in my limited xp means there is a scope issue. Simply means that the place you are referencing the variable can't "see" the variable. Remember that if something is inside curly braces something refrencing from outside cant see it.

Upvotes: 0

Related Questions