Reputation: 1297
I'm trying to write a c sharp program where I enter data to database and read data from database
Database name is kangoojump and I have an admin table here to store id,username and password
I created a login screen for my program and want to type in my username& password and when I press the login button I want to retrieve data from the database table and compare the two and if they match give access to next form...
here is my code
MySqlCommand SelectCommand = new MySqlCommand(" SELECT username FROM kangoojump.admin where _id=1", mcon);
MySqlDataReader myReader;
mcon.Open();
myReader = SelectCommand.ExecuteReader();
while (myReader.Read())
{
temp1 = myReader["username"].ToString();
}
I have created a username,password,temp1,temp2 of type string in my function but
when I try to run the program I get the error that " use of unassigned variable 'temp1' " what is the problem with my code? Thanks
Upvotes: 0
Views: 1266
Reputation: 416149
The problem has to do (in part) with this line of code:
while (myReader.Read())
You and I are smart enough to know that the database query will always return a row, but the compiler is not. This because we have information that is not available to the compiler: we know there will be an admin record. The compiler can't know this. Therefore, the compiler can't guarantee that your code will ever enter the body of that while loop. This means it also can't guarantee that you will ever assign a value to the temp1
variable... hence, your potentially "unassigned variable 'temp1'": the compiler can't guarantee you've written a reasonable value to the variable yet, and you're not allowed to read from it until you do.
The easy solution is to just assign a basic value to the variable when you first declare it:
string temp1 = "";
And while we're here: never ever ever store plain-text passwords. Store one-way password hashes.
Upvotes: 0
Reputation: 79
Where have you defined temp1 ? when defining temp1
do it as follows -
string temp1 = string.Empty;
Upvotes: 1