C# 当从GridView添加DataRow时,如何捕获ConstraintException?
我正在使用DevExpress GridControl创建一个表单,使用户能够进行一些数据输入。网格绑定到一个C# 当从GridView添加DataRow时,如何捕获ConstraintException?,c#,winforms,datatable,gridcontrol,C#,Winforms,Datatable,Gridcontrol,我正在使用DevExpress GridControl创建一个表单,使用户能够进行一些数据输入。网格绑定到一个数据表,其中一列定义为唯一的数据源 DataTable dtDetail = new DataTable(); dtDetail.Columns.Add("ProductID", typeof(int)); dtDetail.Columns.Add("ProductName", typeof(string)); dtDetail.Columns.Add("OrderQty", typeo
数据表
,其中一列定义为唯一的数据源
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.Message中的确切文本,并带有两个YesNo按钮,询问我们是否要更正这些值
我的目标是保持数据表中的所有行都是唯一的。我需要处理约束异常
,以便向最终用户显示自定义错误消息。我搜索了一些关于SO和Microsoft文档的帖子,如以下帖子:
-
-
-
但它并没有告诉我怎么做
有人能帮我怎么做吗?实际上,我的代码运行正常,我只需要处理异常。对不起,我的英语不好。英语不是我的母语。谢谢。当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
并为用户显示自定义错误消息
谢谢。是否在行的上下文中不引发异常。添加函数,因此可能在更新或类似操作时引发异常。尝试基于GridView
创建一个新类,并重写可能抛出错误并使用Try-catch语句扭曲它们的方法。一旦你弄明白了,请告诉我们引发了异常:)你尝试过GridControl的ValidateRow事件吗?@Oleg,我确实使用ValidateRow事件,但目的不同(检查输入值)。但谢谢你给我指出这一点。我可以使用InvalidRowException解决我的需求,如果行验证失败或无法保存到数据源,将引发InvalidRowException,如中所述