以下是从sql中的表中获取值并将其设置为相关字段的代码。但是我想知道如何在下面的块代码中写入条件,所以如果datatable包含USERID,它将在下面执行函数,但如果它没有找到USERID,它应该弹出一条错误消息,说明没有找到User。
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);
}
答案 0 :(得分:1)
if (myReader.Read()) //assuming you only ever have a single result...
{
//set form fields.
}
else
{
//message box
}
根据 @ dmitry-bychenko 的评论修改
答案 1 :(得分:1)
您需要查看if(myReader.HasRows)
if(MyReader.HasRows)
{
while (myReader.Read())
{
//your code here.
}
}
else
{
// your alert.
}