I am a beginner in c# .NET and I am struggling to find an efficient way to catch an unique constraint exception in c# (windows forms).
I am dealing with a combination of three database table columns that are supposed to be unique but I am unable to handle the arising exception on my form.
The code that I am trying on the OnBeforeSaving
Event of my database manager is attached below. Thanks in advance for the help. I am looking for an efficient way to catch the exception(Oracle).
private void dbInstCharges_OnBeforeSaving(object sender, DataManagerSaveArgs e)
{
try
{
this.dbInstCharges.Table.PrimaryKey = new DataColumn[] { dbInstCharges.Table.Columns["EQ17_GC09_ID"], dbInstCharges.Table.Columns["EQ17_CH01_ID"], dbInstCharges.Table.Columns["EQ17_GC05_ID"] };
}
catch (ConstraintException ex)
{
MessageBox.Show(ex.Message);
}
The updated block of code is
private void dbInstCharges_OnBeforeSaving(object sender, DataManagerBeforeSavingArgs e)
{
//e.Record["EQ17_SS01_ID"] = Config.MemberID;
//e.Record["EQ17_EQ16_ID"] = dbManager.CurrentDataRecord["EQ16_ID"];
try
{
UniqueConstraint TableUnique = new UniqueConstraint (new DataColumn[] { dbInstCharges.Table.Columns["EQ17_GC09_ID"], dbInstCharges.Table.Columns["EQ17_CH01_ID"], dbInstCharges.Table.Columns["EQ17_GC05_ID"] });
dbInstCharges.Table.Constraints.Add(TableUnique);
//this.dbInstCharges.Table.PrimaryKey = new DataColumn[] { dbInstCharges.Table.Columns["EQ17_GC09_ID"], dbInstCharges.Table.Columns["EQ17_CH01_ID"], dbInstCharges.Table.Columns["EQ17_GC05_ID"] };
}
catch (Exception ex)
{
MessageBox.Show("Please enter a unique record");
}
}
Code after handling the ArgumentException.
private void dbInstCharges_OnBeforeSaving(object sender, DataManagerBeforeSavingArgs e)
{
//e.Record["EQ17_SS01_ID"] = Config.MemberID;
//e.Record["EQ17_EQ16_ID"] = dbManager.CurrentDataRecord["EQ16_ID"];
try
{
UniqueConstraint TableUnique = new UniqueConstraint(new DataColumn[] { dbInstCharges.Table.Columns["EQ17_GC09_ID"], dbInstCharges.Table.Columns["EQ17_CH01_ID"], dbInstCharges.Table.Columns["EQ17_GC05_ID"], dbInstCharges.Table.Columns["EQ17_SS01_ID"], dbInstCharges.Table.Columns["EQ17_EQ16_ID"] });
dbInstCharges.Table.Constraints.Add(TableUnique);
//this.dbInstCharges.Table.PrimaryKey = new DataColumn[] { dbInstCharges.Table.Columns["EQ17_GC09_ID"], dbInstCharges.Table.Columns["EQ17_CH01_ID"], dbInstCharges.Table.Columns["EQ17_GC05_ID"], dbInstCharges.Table.Columns["EQ17_SS01_ID"], dbInstCharges.Table.Columns["EQ17_EQ16_ID"] };
}
catch (ArgumentException ex)
{
MessageBox.Show("Please enter a unique record");
}
}