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.Empty might be a good choice here too)
If the query returns no results, level would never have been assigned a value.
You can initialise the variable when you declare it to prevent it:
string level = String.Empty;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With