【问题标题】:How to Display Messagebox When No Values Found on SQL在 SQL 上找不到值时如何显示消息框
【发布时间】:2014-07-28 11:01:33
【问题描述】:

以下是从 sql 中的表中获取值并将其设置为相关字段的代码。但是我想知道如何在下面的块代码中编写 if 条件,所以如果数据表包含 USERID,它将执行下面的功能,但如果它没有找到 USERID,它应该弹出一条错误消息,说没有找到用户。

SqlCommand myCommand = new SqlCommand
("SELECT * From USER_TABLE WHERE USERID =" + userIdTextBox.Text, con1);

myReader = myCommand.ExecuteReader();

while (myReader.Read())
{
    nameTextBox.Text = (myReader["FIRST_NAME"].ToString());
    lnameTextBox.Text = (myReader["LAST_NAME"].ToString());
    posTextBox.Text = (myReader["POSITION"].ToString());
    emailTextBox.Text = (myReader["E_MAIL"].ToString());
    phoneTextBox.Text = (myReader["PHONE"].ToString());
    usernameTextBox.Text = (myReader["USERNAME"].ToString());
    userLevelTextBox.Text = (myReader["USER_LEVEL"].ToString());
    string filename = (myReader["PROFILE_PICTURE"].ToString());
    profilePicBox.Load(filename);

}

【问题讨论】:

  • 如果您的查询只能返回一个用户,那么将 WHILE 更改为 IF,然后添加 ELSE 子句以显示错误消息框?

标签: c# sql winforms if-statement


【解决方案1】:

您需要查看if(myReader.HasRows)

  if(MyReader.HasRows)
    {
         while (myReader.Read())
                {
                   //your code here.
                }
    }
    else
    {
      // your alert.
    }

【讨论】:

  • 无需额外检查 (myReader.HasRows):myReader.Read() 如果已读取任何数据,则返回 true
  • @DmitryBychenko,MSDN 声明 Read() 如果有更多行,则返回 true;否则为 false。 因此,如果只有一行,它将返回 false?
  • 不,它返回true:没有记录被读取,并且有一个可以读取。如果没有要读取的记录,Read() 将返回 false - 仅在空光标上
  • @DmitryBychenko,你是对的,在这里检查if(MyReader.Read()) 可能就足够了。如果 OP 想要的不仅仅是一行,我的回答会更合适。
【解决方案2】:
        if (myReader.Read()) //assuming you only ever have a single result...
        {
            //set form fields.
        }
        else
        {
            //message box 
        }

编辑基于来自 @dmitry-bychenko

的评论

【讨论】:

  • 你可以在if中省略myReader.HasRows
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-11-16
  • 2018-03-10
  • 1970-01-01
  • 1970-01-01
  • 2020-11-10
  • 2017-05-15
相关资源
最近更新 更多