0
try
{
    string str = ConfigurationManager.ConnectionStrings["e_con_connection"].ConnectionString;
    SqlConnection con = new SqlConnection(str);
    SqlCommand cmd = new SqlCommand("GetProduct",con);

    cmd.CommandType = System.Data.CommandType.StoredProcedure;
    cmd.Parameters.AddWithValue("@ProductId", productid);

    SqlDataAdapter da = new SqlDataAdapter();
    DataSet ds = new DataSet();
    da.Fill(ds);

}
catch (Exception e)
{
    //throw new Exception( message.ex);

    HttpContext.Current.Response.Redirect("~/Error.aspx?err=" + e.Message);

}


return ds;

i write my code above but show this error whenever i use same code without try catch its work great

the name ds does not exit in the content

Alex
  • 1,993
  • 1
  • 15
  • 25

2 Answers2

2

You must define ds outside the try{} block

 DataSet ds = new DataSet();
    try
    {
       //...
    }
    catch(Exception e)
    {
       //...
    }
Mohsen
  • 196
  • 3
  • 15
1

You are returning ds which mean it needs to be defined before your try starts. There is no guarantee that a specific line inside your try catch block will exist.

Try defining the variable before the try catch and see if that works for you.

DataSet ds = null;
try
{
    string str = ConfigurationManager.ConnectionStrings["e_con_connection"].ConnectionString;
    SqlConnection con = new SqlConnection(str);
    SqlCommand cmd = new SqlCommand("GetProduct",con);

    cmd.CommandType = System.Data.CommandType.StoredProcedure;
    cmd.Parameters.AddWithValue("@ProductId", productid);

    SqlDataAdapter da = new SqlDataAdapter();
    ds = new DataSet();
    da.Fill(ds);
}
catch (Exception e)
{
    //throw new Exception( message.ex);
    HttpContext.Current.Response.Redirect("~/Error.aspx?err=" + e.Message);
}


return ds;
Alex
  • 1,993
  • 1
  • 15
  • 25