我想问。如果在文本框中输入的值在MSSQL数据库中不可用,如何显示消息?我希望用户通知他们输入的值是否存在于数据库中。这是我目前的编码:
private void textBoxEmplNo_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
if (textBoxEmplNo.Text != "")
{
//Do something
textBoxWorkNo.Text = dataGridView1.SelectedRows[0].Cells[2].Value.ToString();
textBoxName.Text = dataGridView1.SelectedRows[0].Cells[0].Value.ToString();
string selectSql = "select icnum, passport, deptno, section from m_employee where empno=@empno";
SqlCommand cmd = new SqlCommand(selectSql, con);
cmd.Parameters.AddWithValue("@empno", textBoxEmplNo.Text);
try
{
con.Open();
using (SqlDataReader read = cmd.ExecuteReader())
{
while (read.Read())
{
textBoxICPass.Text = (read["icnum"].ToString());
textBoxPassport.Text = (read["passport"].ToString());
textBoxDept.Text = (read["deptno"].ToString());
textBoxSection.Text = (read["section"].ToString());
}
}
}
finally
{
con.Close();
}
}
else
{
textBoxWorkNo.Text = "";
textBoxName.Text = "";
}
dataGridView1.Visible = false;
}
}
答案 0 :(得分:2)
我认为布尔变量可以帮助您解决问题。如果是这样,修改后的try块将完成这项工作:
bool isDataFound = false;
try
{
con.Open();
using (SqlDataReader read = cmd.ExecuteReader())
{
while (read.Read())
{
isDataFound = true;
// populate the text boxes here
}
}
if(!isDataFound)
{
// Display message here that no values found
lblError.Text ="No Data Found";
}
}
工作原理:我们有一个初始化为false
的布尔变量,如果是while循环,我们将它们更改为true。然后我们将检查该变量以确定执行时间与否。 if if not表示将根据需要显示消息;
HasRows
类的只读属性SqlDataReader
也可用于此类。在这种情况下,您不需要使用额外的布尔变量,如果读者至少有一行,则HasRows
属性将为true。所以你也可以使用它。以下是该
try
{
con.Open();
using (SqlDataReader read = cmd.ExecuteReader())
{
if(!read.HasRows)
{
// Display message here that no values found
lblError.Text ="No Data Found";
}
else
{
while (read.Read())
{
// populate the text boxes here
}
}
}
}
答案 1 :(得分:0)
试试这个;
如果你有行read.HasRows返回true
using (SqlDataReader read = cmd.ExecuteReader())
{
if (read.HasRows)
{
while (read.Read())
{
textBoxICPass.Text = (read["icnum"].ToString());
textBoxPassport.Text = (read["passport"].ToString());
textBoxDept.Text = (read["deptno"].ToString());
textBoxSection.Text = (read["section"].ToString());
}
}
else
{
lblError.Text = "No Data Found";
}
}
}
答案 2 :(得分:0)
根据其他答案,您可以使用布尔值检查读取是否返回值,然后弹出一个消息框,提醒用户未找到记录。
例如:
using (SqlDataReader read = cmd.ExecuteReader())
{
if (read.read())
{
//display values as you did before
}
else
{
//if using winform include System.Windows.Forms and use
// something like the following,
var result = MessageBox.Show(message, caption,
MessageBoxButtons.YesNo,
MessageBoxIcon.Question);
//depending on the result either cancel the request of prompt
// user for another try.
//If using wpf
// Include Windows.message.messagebox and use the message
// box class in a similar fashion as above. Check usage if
// you are not familiar with it.
}
}
}