当列为主键时,在输入重复项时显示错误消息
本文关键字:显示 消息 错误 输入 | 更新日期: 2023-09-27 18:05:46
就像在名为Emp的表中一样,我有名称列是主键,当我添加重复的名称(巴拉特马里),这已经存在于数据库中,此记录不是在数据库中添加,而是向我显示此消息(员工添加成功)我想向用户显示消息(重复的值不能存储)。我在添加按钮后面使用这个代码,点击
private void button3_Click(object sender, EventArgs e)
{
DBHandling db = new DBHandling();
if (name.Text.Trim().Equals("")&& name.Text.Trim().Equals("select Emp.name from Emp"))
{
name.Focus();
MessageBox.Show("Name cannot be blank or same!");
}
else if(Payment.Text.Trim().Equals(""))
{
Payment.Focus();
MessageBox.Show("Payment cannot be blank!");
}
else if (!IsNumeric(Payment.Text.Trim()))
{
Payment.Focus();
MessageBox.Show("Payment should contain Numerical Values!");
}
else if(CellNumber.Text.Trim().Equals(""))
{
CellNumber.Focus();
MessageBox.Show("Cell Number cannot be blank!");
}
else if (!IsNumeric(CellNumber.Text.Trim()) || CellNumber.Text.Trim().Length<10)
{
CellNumber.Focus();
MessageBox.Show("Invalid Cell Number!");
}
else if(JoiningDate.Text.Trim().Equals(""))
{
JoiningDate.Focus();
MessageBox.Show("set Joining Date!");
}
else
{
db.AddEmp(name.Text, Payment.Text, CellNumber.Text, Education.Text, JoiningDate.Text);
MessageBox.Show("Employee added successfully!");
}
name.Clear();
Payment.Clear();
CellNumber.Clear();
Education.Clear();
name.Focus();
}
那么我该怎么做呢,谢谢。
我正在检查PK使用下面的代码行,我没有得到任何答案,但甚至没有一个错误,你知道任何其他的方式,我应该怎么做?
if (name.Text.Trim().Equals("")&& name.Text.Trim().Equals("select Emp.name from Emp"))
{
name.Focus();
MessageBox.Show("Name cannot be blank or same!");
}
异常方式编写代码是不好的。这会降低应用程序的性能。相反,检查数据库中是否已经存在PK值。甚至可以更快你可以只使用PKs的内部数据结构然后先检查那里如果不存在,再更新加上DB