如何从 GridView 添加数据行时捕获约束异常?



我正在使用DevExpress GridControl创建一个表单,使用户能够进行一些数据输入。网格绑定到一个DataTable,其中一列定义为与其数据源一样唯一。

DataTable dtDetail = new DataTable();
dtDetail.Columns.Add("ProductID", typeof(int));
dtDetail.Columns.Add("ProductName", typeof(string));
dtDetail.Columns.Add("OrderQty", typeof(int));
dtDetail.Columns.Add("LossTolerance", typeof(decimal));
dtDetail.Columns["ProductID"].Unique = true;
gridView.DataSource = dt;

通常我们可以使用以下代码添加行并处理约束冲突:

try
{    
dtDetail.Rows.Add(1, "Some product name", 10, 2);
}
catch (ConstraintException ex)
{
// The default ex.Message is something like: Column 'ProductID' is constrained to be unique. Value xxxx is already present. 
// I need to display this message in my local language.
}

我设计的表单是数据输入表单,因此数据通过网格来自最终用户。当用户添加行时,以某种方式调用dtDetail.Rows.Add方法,我不知道如何正确处理ConstraintException,因为添加的行来自网格,而不是直接来自我的代码。

当要添加重复ProductID时,将显示一个MessageBox,其中包含 ex 中的确切文本。消息,带有两个"是否"按钮,询问我们是否要更正值。

我的目标是保持DataTable内的所有行都是唯一的。我需要处理ConstraintException,以便向最终用户显示自定义错误消息。我已经搜索了一些关于SO和Microsoft文档的帖子,例如这些帖子:

  • 约束异常类

  • 数据表约束

  • 如何在 C# 中添加记录时处理数据表中的唯一约束异常

但它并没有给我如何做到这一点的线索。

谁能帮我怎么做?实际上,我的代码运行正常,我只需要处理异常。对不起,我的英语不好。英语不是我的母语。谢谢。

正如 Oleg 在评论部分评论以使用该事件ValidateRow,我能够使用与该事件实际相关的另一个事件来解决我的需求,这是InvalidRowException

private void gridView_InvalidRowException(object sender, DevExpress.XtraGrid.Views.Base.InvalidRowExceptionEventArgs e)
{
// Get the type of exception
if (e.Exception.GetType() == typeof(ConstraintException))
{
// Get the unique constraint column
using (DataColumn constraintColumn = ((UniqueConstraint)dtDetail.Constraints[0]).Columns[0])
{
// Get the value that violates unique constraint
object value = ((DataRowView)e.Row).Row[constraintColumn];
DialogResult dr = XtraMessageBox.Show(string.Format("Kolom {0} diatur sebagai Unique. Nilai {1} telah ada sebelumnya. Apakah Anda ingin memperbaiki barisnya?", constraintColumn.ColumnName, value.ToString()), "Informasi", MessageBoxButtons.YesNo, MessageBoxIcon.Information);
if (dr == DialogResult.Yes)
{
// No action. User can correct their input.
e.ExceptionMode = DevExpress.XtraEditors.Controls.ExceptionMode.NoAction;
}
else
{
// Duplicate row will be removed
e.ExceptionMode = DevExpress.XtraEditors.Controls.ExceptionMode.Ignore;
}
}
}
}

通过使用上面的代码,我可以处理ConstraintException并为我的用户显示自定义错误消息。

谢谢。

最新更新