Semil Sebastian
Semil Sebastian

Reputation: 39

The Name 'data' does not exist in the current context

I am trying to generate a try catch method in a class, But I am facing this error message, Please help me to solve this. My class is

public string Countryadd(string country, string id)
{

     try
     {
         string data="0";
         string qry1 = "select Country from Country where Country='" + country + "'";//Checking weather txtcountry(Country Name) value is already exixst or not. If exist return 1 and not exists go to else condition
         SqlDataReader dr = conn.query(qry1);
         if (dr.Read())
         {
             return data = "1";
         }
         else//If Country Name Not Exists
         {
             string qry = "insert into Country values('" + id + "','" + country + "')";//Insertin data into database Table Country
             conn.nonquery(qry);
         }

     }
     catch (Exception Ex)
     {
         ShowPopUpMsg(Ex.Message);
     }
     return data;
 }

Upvotes: 1

Views: 2680

Answers (5)

Sayse
Sayse

Reputation: 43300

data is currently defined within the scope of the try block, you need to move it outside

string data = "0";
try
{
...
}
catch(NullReferenceException ex)
{
}
catch(SomethingRelatedToDataReaderException ex)
{
}
return data;

Also, you shouldn't really try to catch Exception, you should try to catch the specific types of exceptions. This helps to avoid covering up issues as well as giving you more control

Upvotes: 2

Soner Gönül
Soner Gönül

Reputation: 98750

Since you define your data variable in try block, it doesn't seems outside of this blocks. It is only available in try block and any child scope.

You can move it's definition outside of your try-catch block.

string data="0";
try
{
   ...
}
catch (Exception Ex)
{
     ShowPopUpMsg(Ex.Message);
}
return data;

Read: 3.7 Scopes (C#) from MSDN

Upvotes: 4

Razlo3p
Razlo3p

Reputation: 487

The scoping of your variable data is only inside the Try/Catch block because you defined in it.

Try to define the variable data outsiude the block.

Upvotes: 0

Nahuel Ianni
Nahuel Ianni

Reputation: 3185

All variables created between the { } symbols are inside the scope of the symbols themselves.

If you need to use data outside of it, declare it before the try.

string data = string.Empty; // or initialize the value to "0" if that's the default you want.

try
{
   // Don't declare data here or it won't be visible outside the try block.
   // You can set the "0" or whatever value you want here though.
   ...
}

catch (Exception Ex)
{
   ...
}

return data;

Upvotes: 2

thumbmunkeys
thumbmunkeys

Reputation: 20764

You need to put the definition of data before the try block:

   string data="0";

   try {

The {} brackets define the scope of a variable.

You can only access a variable within that scope.

Upvotes: 5

Related Questions