Newbie question

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?
 
G

Guest

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.
 
S

Stijn Verrept

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.
 
W

William F. Robertson, Jr.

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,780
Messages
2,569,611
Members
45,280
Latest member
BGBBrock56

Latest Threads

Top