Ruben rj
Ruben rj

Reputation: 27

The Value stored inside while(read()) loop is unable to retrieve the value outside while loop

How do do you retrieve the data after a while loop?

con220.Open();
SqlDataReader rdr2 = cmd220.ExecuteReader();

while (rdr2.Read())
{
    TAT = rdr["TAT"].ToString();            
}

con220.Close();
MessageBox.Show(TAT);//ERROR: use of unassigned local variable TAT

Upvotes: 0

Views: 67

Answers (2)

Zein Makki
Zein Makki

Reputation: 30042

The Compiler has to verify that the local variable is assigned in all the paths that might execute. In your case the while block might not be executed if the reader returned empty results. So the compiler can't really verify the TAT is guaranteed to be assigned.

So you can do this before the while loop.

string TAT = null;

Upvotes: 1

mohi
mohi

Reputation: 64

string TAT = string.Empty; 
while (rdr2.Read())
{
     TAT = rdr["TAT"].ToString();
}

con220.Close();
MessageBox.Show(TAT);

Upvotes: 1

Related Questions