HI.I搜索了这个问题通知我找到了更改列属性的解决方案Unique Index.Now如果我尝试插入相同的记录cmd.ExecuteNonQuery()
给出了记录存在的错误,但如何使用此异常给用户一个记录存在的消息,必须输入新记录?我想做一些像
if(cmd.ExecuteNonQuery() !=true )
{
MessageBox.Show("User Exists");
}
但我不知道返回cmd.ExecuteNonQuery()
的是什么?
或者我必须在表格中使用阅读器获取记录并将其与Textfiel中的文本进行比较?
答案 0 :(得分:1)
你可以在你拥有的代码块周围放置一个try catch块,然后查看异常类型,然后在catch中使用Exception而不是使用Exception,你可以使用你想要捕获的显式异常。
try
{
cmd.ExecuteNonQuery();
}
catch(Exception ex)
{
ex.Type.ToString(); //this will give you the type of exception.
}
现在,一旦你知道异常是什么,你只能抓住那个,并告知用户如下。
try
{
cmd.ExecuteNonQuery();
}
catch(RecordExhistsException ex)
{
MessageBox.Show("Duplicate Record");
}
享受!
答案 1 :(得分:1)
cmd.CommandText = "Select * from Emp";
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
DartaReader dr;
dr = cmd.ExecuteReader();
while (dr.Read())
{//textbox contain the id or name which you want to check in table
if (dr[0].ToString() == textBox1.Text)
{
MessageBox.Show("Record is Already Exist");
con.Close();
break;
}
}
通过使用上面的代码我发现数据库表中存在记录。