private void button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection();
con.ConnectionString = "Data Source=asa-PC\\SQLEXPRESS;Initial Catalog=table1;Integrated Security=True";
con.Open();
SqlCommand cmd = new SqlCommand("select * from worker where number='" + textBox1.Text.Trim() + "'", con);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
textBox2.Text = dr[0].ToString();
textBox3.Text = dr[1].ToString();
MessageBox.Show("No record is found with this number >> " + textBox1.Text.ToString());
}
}
}
}
你好,伙计们能帮助我吗? 如果没有找到记录但我不知道如何在代码中包含IF,我需要MessageBox来显示此消息 如果用户放了更多,则textbox1的最大数字或字母为10,然后将出现MessageBox(max10)答案 0 :(得分:0)
您可以使用SqlDataReader.HasRows
属性来确定是否返回了任何记录。像:
if (dr.HasRows)
{
while (dr.Read())
{
textBox2.Text = dr[0].ToString();
textBox3.Text = dr[1].ToString();
}
}
else
{
MessageBox.Show("No record is found with this number >> " + textBox1.Text.ToString());
}
但还有几件事要补充:
不确定如何在TextBox
控件中显示多条记录,您可能需要网格或将返回的行/记录添加到List<T>
或List<Worker>
其中Worker
类可以具有列的属性。
在SqlCommand
/ SqlConnection
和SqlDataReader
实施IDisposable
时使用using
statement
dr[0].ToString()
可能会抛出Null Reference Exception,研究并了解如何保护它。 所以你的代码或多或少应该是这样的:
private void button1_Click(object sender, EventArgs e)
{
using (SqlConnection con = new SqlConnection())
{
con.ConnectionString = "Data Source=asa-PC\\SQLEXPRESS;Initial Catalog=table1;Integrated Security=True";
con.Open();
using (SqlCommand cmd = new SqlCommand("select * from worker where number=@Number", con))
{
cmd.Parameters.AddWithValue("@Number", textBox1.Text);//or explicity specify type using .Add
using (SqlDataReader dr = cmd.ExecuteReader())
{
if (dr.HasRows)
{
while (dr.Read())
{
//Add to List<Worker> with properties Name and Number etc
textBox2.Text = dr[0].ToString();
textBox3.Text = dr[1].ToString();
}
}
else
{
MessageBox.Show("No record is found with this number >> " + textBox1.Text.ToString());
}
}
}
}
}