Error cs0103 the name facingright does not exist in the current context

This repository contains .NET Documentation. Contribute to dotnet/docs development by creating an account on GitHub.

Permalink

Cannot retrieve contributors at this time

description title ms.date f1_keywords helpviewer_keywords ms.assetid

Compiler Error CS0103

Compiler Error CS0103

07/20/2015

CS0103

CS0103

fd1f2104-a945-4dba-8137-8ef869826062

Compiler Error CS0103

The name ‘identifier’ does not exist in the current context

An attempt was made to use a name that does not exist in the class, namespace, or scope. Check the spelling of the name and check your using directives and assembly references to make sure that the name that you are trying to use is available.

This error frequently occurs if you declare a variable in a loop or a try or if block and then attempt to access it from an enclosing code block or a separate code block, as shown in the following example:

[!NOTE]
This error may also be presented when missing the greater than symbol in the operator => in an expression lambda. For more information, see expression lambdas.

using System;

class MyClass1
{
    public static void Main()
    {
        try
        {
            // The following declaration is only available inside the try block.
            var conn = new MyClass1();
        }
        catch (Exception e)
        {  
            // The following expression causes error CS0103, because variable
            // conn only exists in the try block.
            if (conn != null)
                Console.WriteLine("{0}", e);
        }
    }
}

The following example resolves the error:

using System;

class MyClass2
{
    public static void Main()
    {
        // To resolve the error in the example, the first step is to
        // move the declaration of conn out of the try block. The following
        // declaration is available throughout the Main method.
        MyClass2 conn = null;
        try
        {
            // Inside the try block, use the conn variable that you declared
            // previously.
            conn = new MyClass2();
        }
        catch (Exception e)
        {
            // The following expression no longer causes an error, because
            // the declaration of conn is in scope.
            if (conn != null)
                Console.WriteLine("{0}", e);
        }
    }
}

So, I’m working on this project between my laptop and my desktop.

The project works on the laptop, but now having copied the updated source code onto the desktop, I have over 500 errors in the project, all of them are…

The name does not exist in the current context

Here’s one example…

Jobs.aspx

<%@ Page Title="" Language="C#" MasterPageFile="~/Members/Members.master" AutoEventWireup="true" CodeFile="Jobs.aspx.cs" Inherits="Members_Jobs" %>

<%@ Register Namespace="AjaxControlToolkit" Assembly="AjaxControlToolkit" TagPrefix="aj" %>

<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
    <asp:UpdatePanel runat="server" ID="upJobs">
        <ContentTemplate>
            <!-- page content goes here -->
        </ContentTemplate>
    </asp:UpdatePanel>
</asp:Content>

Jobs.aspx.cs

public partial class Members_Jobs : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            loadJobs();
            gvItems.Visible = false;
            loadComplexes();
            loadBusinesses();
            loadSubcontractors();
            loadInsurers();

            pnlCallback.Visible = false;
            pnlInsurer.Visible = false;
        }
    }

    // more goes down here
}

Here’s a sample of the designer.cs file…

namespace stman.Members {


    public partial class Jobs {

        /// <summary>
        /// upJobs control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.UpdatePanel upJobs;
    }
}

I know this error means that the control being referenced generally doesn’t exist or is not a part of the class that’s referencing it, but as far as I can see, that isn’t the case here.

Can anyone provide some insight?

VS2012 Screenshot

C# Compiler Error

CS0103 – The name ‘identifier’ does not exist in the current context

Reason for the Error

You will usually receive this error when you are trying to use a identifier name in C# that doesnot exist with-in the current scope. One of the simple example of this error is when you declare a variable with-in a try block and try to access it in the catch block.

In the below example, the variable i is declared inside the try block, so its scope is restricted to the try block. When you try accessing it in the catch block is when you will receive the error.

using System;

public class DeveloperPublish
{
    public static void Main()
    {       
        try
        {
            int i = 1;
            int j = 0;
            int result = i / j;
        }
        catch(DivideByZeroException)
        {
            string message = i + " is divivided by zero";
            Console.WriteLine(message);
        }

    }
}

Error CS0103 The name ‘i’ does not exist in the current context ConsoleApp1 C:UsersSenthilsourcereposConsoleApp1ConsoleApp1Program.cs 16 Active

Solution

To fix the error move the declaration of the identifier that is causing the error to a higher scope so that it is available when it is accessed.

For example, to fix the error in the above code snippet, we just need to move the declaration of the identifier outside of the try block.

using System;

public class DeveloperPublish
{
    public static void Main()
    {
        int i = 1;
        try
        {          
            int j = 0;
            int result = i / j;
        }
        catch(DivideByZeroException)
        {
            string message = i + " is divivided by zero";
            Console.WriteLine(message);
        }

    }
}

0 / 0 / 0

Регистрация: 03.03.2019

Сообщений: 7

1

03.03.2019, 22:27. Показов 13926. Ответов 11


Всем привет, перечитал много тем по поводу данной ошибки, но у меня немного другая ситуация, код компилируется нормально, без ошибок, но при запуске сервера выдает уже ошибки
Например у меня есть класс где функции транспорта, когда при запуске сервера я вызываю загрузку транспорта — выходит ошибка

Код

CS0103: The name 'VehicleF' does not exist in the current context -> Class1.cs:16

Файл запуска сервера

C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
using System;
using GTANetworkAPI;
 
namespace NewProject
{
    public class Main : Script
    {
        [ServerEvent(Event.ResourceStart)]
        public void OnResourceStart()
        {
            NAPI.Util.ConsoleOutput("Сервер успешно запущен");
            NAPI.Server.SetDefaultSpawnLocation(new Vector3(386.4574, -750.8737, 29.29371));
            VehicleF.LoadVehicle();
        }
    }
}

Файл с функциями транспорта

C#
1
2
3
4
5
6
7
8
9
10
11
12
13
using GTANetworkAPI;
 
namespace NewProject
{
    public class VehicleF : Script
    {
        public static void LoadVehicle()
        {
            NAPI.Vehicle.CreateVehicle(NAPI.Util.VehicleNameToModel("CarbonRS"), new Vector3(380.8715, -739.8875, 28.88084), 179, new Color(0, 255, 100), new Color(0));
            NAPI.Util.ConsoleOutput("[LOAD] Транспорт успешно запущен");
        }
    }
}

А так же где у меня идет работа с базой данных выходит ошибка

Код

 CS0012: The type 'DbConnection' is defined in an assembly that is not referenced. You must add a reference to assembly 'System.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'.
       -> connect.cs:15

Добавлено через 1 час 24 минуты
Большое спасибо вам, но я перехожу по вашим ссылкам, там такие же ответы на другие ссылки, а затем опять ответы со ссылками, где-то на 5 переходе я бросил это занятие, так как видимо ответов здесь не бывает -_-

Добавлено через 9 минут
Тем более меня не интересуют темы где люди не обьявляют переменные, меня интересует почему у меня методы из одного класса не вызываются в другом, классы по разным файлам

Добавлено через 16 минут
Если я прописываю два класса в одном файле то все хорошо, а если по разным то вот такие ошибки, может кто сказать как линкануть файл? Указать его вначале? Подключить? Я думал что если все одним проектом то таких проблем быть не должно, но видимо ошибся

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь



0



  • Remove From My Forums
  • Question

  • User397255882 posted

    My asp.net page runs fine in VWD Express 2010 but on the server i get this error:

    error CS0103: The name 'DropDownList_Nodes' does not exist in the current context
    If anyone can help me I would appreciate it.
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Data;
    using System.Data.SqlClient;
    
    namespace OrionNodeEvent
    {
        public partial class _Default : System.Web.UI.Page
        {
            protected void Page_Load(object sender, EventArgs e)
            {     
                if (!this.IsPostBack)//only do on 1st page load
                {
                    FillListBox();
                }            
            }//end Page_Load
    
            protected void Submit_Click(object sender, EventArgs e)
            {
                string connectionString = @"data source=****;initial catalog=****;user id=*****;" +
                        "password=****;packet size=4096;persist security info=False;connect timeout=30000; Trusted_Connection=yes";            
                string insertSQL;
                DateTime currentTime = DateTime.UtcNow; 
                insertSQL = @"USE **** INSERT INTO ***** (";
                insertSQL += "Node_Name, Event, Solution, Time) ";
                insertSQL += "VALUES ('";            
                insertSQL += DropDownList_Nodes.SelectedItem.ToString()  + "', '";
                insertSQL += TextBox_Event.Text + "', '";
                insertSQL += TextBox_Solution.Text + "', '";
                insertSQL += currentTime + "')";
    
                SqlConnection sql_connection = new SqlConnection(connectionString);
                SqlCommand sql_command = new SqlCommand(insertSQL, sql_connection);
    
                int added = 0;//counter for rows inserted to DB
                try
                {                
                    sql_connection.Open();
                    added = sql_command.ExecuteNonQuery();
                    Label_Info.Text = added.ToString() + " records inserted.";
                }
                catch(Exception error)
                {
                    Label_Info.Text = error.Message;                
                }
                finally
                {
                    sql_connection.Close();
                    sql_connection.Dispose();
                }
                 
            }//end Submit_Click
            protected void FillListBox()
            {
                string connectionString = @"data source=****;initial catalog=****;user id=****;" +
                        "password=****;packet size=4096;persist security info=False;connect timeout=30000; Trusted_Connection=yes";
                
                DropDownList_Nodes.Items.Clear();
                string selectSQL = @"USE **** SELECT ***, *** FROM *** ORDER BY ***";
    
                SqlConnection sql_connection = new SqlConnection(connectionString);
                SqlCommand sql_command = new SqlCommand(selectSQL, sql_connection);
                SqlDataReader sql_reader;
                  try
                {                
                    sql_connection.Open();
                    sql_reader = sql_command.ExecuteReader();
                    while (sql_reader.Read())
                    {
                        ListItem newitem = new ListItem();
                        newitem.Text = sql_reader["****"].ToString();
                        newitem.Value = sql_reader["****"].ToString();
                        DropDownList_Nodes.Items.Add(newitem);
                    }//end while
                    sql_reader.Close();
                    sql_reader.Dispose();
                }//end try
                catch(Exception error)
                {
                    Label_Info.Text = error.Message;               
                }
                finally
                {
                    sql_connection.Close();
                    sql_connection.Dispose();
                }
            }//end FillListBox
      	public override void VerifyRenderingInServerForm(Control control)
            {
                return;
            }
        }//end public partial class _Default : System.Web.UI.Page
    }//end namespace OrionNodeEvent
    
    // ASP PAGE ***************************************
    
    <%@  Language="C#"  AutoEventWireup="true"
        CodeBehind="OrionNodeEvent.aspx.cs" Inherits="OrionNodeEvent._Default" Src="OrionNodeEvent.aspx.cs" %>    
    
        <html>
        <head>
        <title>Orionz</title>
        </head>
        <body>
    
        <h2>Select a Node to add an event and resolution.</h2>   
        <p><asp:DropDownList ID="DropDownList_Nodes" runat="server"></asp:DropDownList></p>
       <p><strong>Event</strong><asp:TextBox ID="TextBox_Event" runat="server" style="margin-left: 25px" 
                Width="500px" Height="150px" TextMode="MultiLine" MaxLength="8000"></asp:TextBox></p>
       <p><strong>Solution</strong><asp:TextBox ID="TextBox_Solution" runat="server" 
                style="margin-left: 10px" Width="500px" Height="150px" TextMode="MultiLine" MaxLength="8000"></asp:TextBox> </p>         
       <p><asp:Button ID="Button_Submit" runat="server" Text="Submit" OnClick="Submit_Click"/></p>
        <p><asp:Label ID="Label_Info" runat="server" Text="" ></asp:Label> </p>
        </body>
        </html>
    
    

Answers

  • User397255882 posted

    SOLVED:

    Added these control statements to the Default.aspx.cs:

    protected global::System.Web.UI.HtmlControls.HtmlForm form1;
    protected System.Web.UI.WebControls.Label Label_Info; 
    protected System.Web.UI.WebControls.DropDownList DropDownList_Nodes;
    protected System.Web.UI.WebControls.TextBox TextBox_Event;
    protected System.Web.UI.WebControls.TextBox TextBox_Solution;
    protected System.Web.UI.WebControls.Button Button_Submit;

    The server was ignoring the designer file.

    Now it loads!

    • Marked as answer by

      Thursday, October 7, 2021 12:00 AM

Скрипт не работает

Скрипт не работает

Вот такой простенький скрипт но консоль выдает данную ошибку=Assets/M2.cs(8,20): error CS0103: The name `col’ does not exist in the current context
И еще желтую ошибку=Assets/M2.cs(10,28): warning CS0219: The variable `rotationY’ is assigned but its value is never used

Используется csharp

using System.Collections;

public class Moving2 : MonoBehaviour {

       
        void Update ()
        {          
                if(col.gameObject.name == «RollerBall»)
                {
                Quaternion rotationY = Quaternion.AngleAxis (180, Vector3.up);

                       
                }
        }
}

developers
UNец
 
Сообщения: 15
Зарегистрирован: 30 янв 2016, 22:55

Re: Скрипт не работает

Сообщение Smouk 03 мар 2016, 10:36

1. Из этого не понять в чем именно ошибка. Где объявлено col и зачем? Для получения имени объекта если скрипт висит на нем это не нужно.
В принципе не очень верно каждый update без необходимости сравнивать текст. Лучше при создании объекта использовать флаг или int с типом объекта, например.
2. Если перевести там прямо написано, что переменная rotationY никогда не используется.

Последний раз редактировалось Smouk 03 мар 2016, 10:39, всего редактировалось 2 раз(а).

Smouk
UNIт
 
Сообщения: 146
Зарегистрирован: 16 сен 2009, 08:47

Re: Скрипт не работает

Сообщение BladeBloodShot 03 мар 2016, 10:38

Ну так переведи ошибки, нет определения col то бишь надо public var col = там чему то;

BladeBloodShot
UNец
 
Сообщения: 38
Зарегистрирован: 03 фев 2016, 22:31



Re: Скрипт не работает

Сообщение developers 03 мар 2016, 12:06

А насчет 2 причины

developers
UNец
 
Сообщения: 15
Зарегистрирован: 30 янв 2016, 22:55

Re: Скрипт не работает

Сообщение iLLoren 03 мар 2016, 13:59

developers писал(а):А насчет 2 причины

Научись разбираться с мелочами самостоятельно, тебе самому то не стыдно что имея видео о том как с 0 сделать всё правильно ты косячишь и вместо пересмотров урока ты плачешь на форуме о проблемах которые сам можешь легко решить?

Аватара пользователя
iLLoren
UNIт
 
Сообщения: 103
Зарегистрирован: 31 дек 2015, 12:00

Re: Скрипт не работает

Сообщение Tolking 03 мар 2016, 14:16

Желтая ошибка называется предупреждением и в переводе с английского гласит: ты нахрена опредилил переменную `rotationY’ если нигде ее не используешь!

Таки да!!! Английский знать надо или пользоваться переводчиком…

Ковчег построил любитель, профессионалы построили Титаник.

Аватара пользователя
Tolking
Адепт
 
Сообщения: 2684
Зарегистрирован: 08 июн 2009, 18:22
Откуда: Тула


Вернуться в Скрипты

Кто сейчас на конференции

Сейчас этот форум просматривают: нет зарегистрированных пользователей и гости: 6



Понравилась статья? Поделить с друзьями:

Читайте также:

  • Error creating session парус 10
  • Error creating remote thread code 0 advor
  • Error creating registry key hkey local machine
  • Error creating project xsrf check failed
  • Error creating process не удается найти указанный файл directx

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии