0

I have this:

 countReader = command7.ExecuteReader();
 while (countReader.Read())
 {
    string countName = countReader["count(*)"].ToString();                
 }

How to get string countName outside while loop?

1
  • What is "count(*)"? That doesn't look like a valid column name to me. Are you trying to get the sum of that column? If not, what are you trying to accomplish? Commented Sep 4, 2011 at 10:14

3 Answers 3

1

If you want to access a variable outside the while loop you should declare it outside like this

countReader = command7.ExecuteReader();
string countName = String.Empty;

 while (countReader.Read())
 {
  countName = countReader["count(*)"].ToString();                
 }
Sign up to request clarification or add additional context in comments.

Comments

1

You could declare it in the outer scope:

countReader = command7.ExecuteReader();
string countName = "";
while (countReader.Read())
{
    countName = countReader["count(*)"].ToString();                
}
// you can use countName here

Note that because you are overwriting its value on each iteration, outside the loop you will get its value from the last iteration or an empty string if the loop didn't execute.

2 Comments

If i may suggest somenthing. One change "" to String.Empty.
+1 for noting that the countName will be overwritten on each loop, if there's more than one row in the reader.
0
string countName;
countReader = command7.ExecuteReader();
while (countReader.Read())
{
   countName = countReader["count(*)"].ToString();                
}

The scope will mean it is still accessible after the loop is exited.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.