Newbie question

  • Thread starter Thread starter Stijn Verrept
  • Start date Start date
S

Stijn Verrept

I have this code:

bool Found = false;

if (TextBox1.Text.Length > 0)
{
SqlConnection conn = new SqlConnection(ConnectionString);

SqlCommand cmd = new SqlCommand("[GetSVZList]", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("@File", SqlDbType.Int);
cmd.Parameters["@File"].Value = TextBox1.Text;
cmd.Parameters.Add("@TPID", SqlDbType.Int);
cmd.Parameters["@TPID"].Value = Session["VisitorsID"];

try
{
conn.Open();
SqlDataReader reader = cmd.ExecuteReader();

if (reader.HasRows) {Found = true;}
else {
reader.Close();
SqlCommand cmd2 = new SqlCommand("[GetSVZList2]", conn);

cmd2.CommandType = CommandType.StoredProcedure;

cmd2.Parameters.Add( "@SearchString", SqlDbType.VarChar, 30);
cmd2.Parameters.Add("@TPID", SqlDbType.Int);
cmd2.Parameters["@TPID"].Value = Session["VisitorsID"];
SqlDataReader reader2 = cmd2.ExecuteReader();
if (reader2.HasRows) {Found = true;}
}

if (!Found) {Label5.Text = "No records found!";}
else {
Panel2.Visible = true;
Panel1.Visible = false;
Label5.Text = "";
Label2.Text = "Current file: " + TextBox1.Text;
if (reader.IsClosed) {DataGrid2.DataSource = reader2;} else
{DataGrid2.DataSource = reader;}
DataGrid2.DataBind();
}
}
finally { sqlConnection1.Dispose(); }

I get the message: The name 'reader2' does not exist in the class or
namespace 'ICS.Files'. Why is this? I create it with SqlDataReader
reader2 = cmd2.ExecuteReader(); or not? What's wrong?
 
Hey Stijn

Reader2 is declared within the scope of your first else-block. Hence it can not be used outside this scope. Therefore you are getting the compile error when you are trying to use reader2 in the second else-block

Regards, Jakob.
 
Jakob said:
Hey Stijn.

Reader2 is declared within the scope of your first else-block. Hence
it can not be used outside this scope. Therefore you are getting the
compile error when you are trying to use reader2 in the second
else-block.

Regards, Jakob.

Aha, ok thanks. Is there any way to re-use "reader" for that purpose?
I want to check one stored procedure first and if it's empty check a
second and then connect the one that contains data to the grid.
 
Easiest way is to declare

SqlDataReader reader = null;

at the top of your method.

HTH,

bill

on a side note, you might want to look into ExecuteScalar() if you are not
going to do anything with the data for the first reader. It will return
DbNull if there are no rows, and I believe it is a faster operation.
 
Back
Top