I am using DevExpress GridControl to create a form that enable user to do some data entry. The grid is bound to a DataTable
with one column defined as unique as its DataSource.
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;
Normally we can add rows and handle constraint violation with this code:
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.
}
The form I designed is a data entry form, so the data comes from end user through the grid. When row is added by user, the dtDetail.Rows.Add
method is called in some way and I don't know how to handle the ConstraintException
properly, since the added row is coming from grid, not directly from my code.
When duplicate ProductID
is about to added, a MessageBox
will appear with exact text in ex.Message, with two YesNo buttons, asking us whether we want to correct the values or not.
My goal is to keep all rows within the DataTable
is unique. I need to handle the ConstraintException
so I can display custom error message to end user. I have searched some post on SO and Microsoft documentation like these posts:
but it doesn't give me clue on how to do that.
Could anyone please assist me how to do that? Actually, my code is running properly, I just need to handle the exception. Sorry for my bad English. English is not my native language. Thank you.