在我检查记录后,读者无法继续

时间:2012-07-12 06:32:23

标签: c# database null

我已成功检查数据库中是否有值。

以下是代码:

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;
    }
}

但问题是无论如何都会跳过while循环。

3 个答案:

答案 0 :(得分:5)

替换

if (!reader.Read())

if (!reader.HasRows)

答案 1 :(得分:2)

我会设置循环,以便您在一个位置调用Read,然后检查count

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

我已移除reader.Close()来电 - 只要您的readerusing声明中(应该是),它就会自动关闭。

答案 2 :(得分:0)

你不应该使用reader.Read()两次,只使用一次

if (!reader.HasRows)
                {
                    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;

                    }
                }