Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reader cannot continue after i've checked for records

Tags:

c#

database

null

I have successfully checked that there are values in the database.

Here is the code:

if (!reader.Read())
{
    MessageBox.Show(" Can not find user!");
    reader.Close();
}
else
{
    int count = 0;
    while (reader.Read())
    {
        string user = (string)reader.GetString(0);
        string name = (string)reader.GetString(1);
        int roll = (int)reader.GetInt32(2);
        string phone = (string)reader.GetString(3);
        string address = (string)reader.GetString(4);
        string birthofdate = (string)reader.GetString(5);
        label1.Text = "" + roll;
        label2.Text = name;
        label3.Text = birthofdate;
        label4.Text = "" + phone;
        label5.Text = address;
    }
}

But the problem is that the while loop is skipped anyway.

like image 382
famfamfam Avatar asked Apr 19 '26 20:04

famfamfam


2 Answers

Replace

if (!reader.Read())

with

if (!reader.HasRows)
like image 103
Ivan Golović Avatar answered Apr 21 '26 11:04

Ivan Golović


I would just have the loop so you call Read in one place, and check count afterwards:

int count = 0;
while (reader.Read())
{
    ...
}
if (count == 0)
{
    MessageBox.Show(" Can not find user!");
}

I've removed the reader.Close() call - so long as your reader is in a using statement (which it should be) it'll be closed automatically.

like image 43
Jon Skeet Avatar answered Apr 21 '26 11:04

Jon Skeet