What’s wrong with the code?
Why on the second report shows a mistake?
string level;
int key;
command.CommandText = "SELECT * FROM user WHERE name = 'admin'";
connection.Open();
Reader = command.ExecuteReader();
while (Reader.Read())
{
level = Convert.ToString(Reader["level"]);
key = Convert.ToInt32(Reader["key"]);
MessageBox.Show(level); //Work fine
}
MessageBox.Show(level); //Show error: Use of unassigned local variable 'level'
The compiler has no way of knowing level got a value. For all it knows,
Reader.Read()always returns false, thus leaving level without a value.The most common solution to this is to just initialize level to
null(or I agree with AdaTheDev,string.Emptymight be a good choice here too)