这是我的代码。当我输入一个不存在的ID时,会出现一条错误消息。当程序意识到此ID不存在时,我想显示一个消息框。
public Form1()
{
InitializeComponent();
}
private void label1_Click(object sender, EventArgs e)
{
}
private void BTN_INSERT_Click(object sender, EventArgs e)
{
String selectquery = "SELECT * FROM imgbase.Clients WHERE ID = '" + BOX_ID.Text + "' ";
command = new MySqlCommand(selectquery, connection);
da = new MySqlDataAdapter(command);
DataTable table = new DataTable();
da.Fill(table);
BOX_FULLNAME.Text = table.Rows[0][1].ToString();
BOX_INFO.Text = table.Rows[0][2].ToString();
byte[] img = (byte[])table.Rows[0][3];
MemoryStream ms = new MemoryStream(img);
pictureBox1.Image = Image.FromStream(ms);
da.Dispose();
}
答案 0 :(得分:1)
所以你可以使用
try{
if(table.Rows.Count == 0)
{ MessageBox.Show("No Records with given ID ...");
return;
}
}
catch{
error message;
}
答案 1 :(得分:0)
如果ID
不存在,那么您将获取0行或记录。在这种情况下,您可以检查Rows
的{{1}}属性
DataTable
顺便说一句,停止使用连接查询和易受 SQL注入攻击的用户输入,而不是使用if(table.Rows.Count == 0)
MessageBox.Show("No Records with given ID ...");
SqlParameter
填写数据表之后只需检查返回的行数。如果获取的行然后执行处理,则抛出消息并返回调用者。
String selectquery = "SELECT * FROM imgbase.Clients WHERE ID = @ID";
command = new MySqlCommand(selectquery, connection);
MySqlParameter param = new MySqlParameter();
param.ParameterName = "@ID";
param.Value = Convert.ToInt32(BOX_ID.Text.Trim());
command.Parameters.Add(param);