At one time or another, many of us who have worked with DataSets in .NET have received this foreboding message:
Failed to enable constraints. One or more rows contain values violating non-null, unique, or foreign-key constraints.
I’ll go out on a limb here and say we probably all agree it’s not an incredibly useful message. So how do you find out what the heck actually happened to cause the error?
Error messages (real error messages, not the exceptionally “helpful” one above) in DataSets are stored at the column and row levels within the tables in the DataSet. Therefore, you can use diagnostic code such as the following to get these messages:
using System.Collections.Specialized; // for NameValueCollection class
...
try
{
// code that throws DataSet exception
}
catch
{
// print out a list of the "real" error messages in the DataSet
NameValueCollection c = BuildDataSetErrorInfo(myDataSet);
foreach (string name in c)
{
System.Diagnostics.Debug.WriteLine(name + c[name]);
}
}
...
private static NameValueCollection BuildDataSetErrorInfo(DataSet dataSet)
{
NameValueCollection errorInfo = new NameValueCollection();
errorInfo.Add("DataSetName: ", dataSet.DataSetName);
foreach (DataTable table in dataSet.Tables)
{
DataRow[] rows = table.GetErrors();
if ((rows != null) && (rows.Length > 0))
{
errorInfo.Add(" - Table: ", table.TableName);
foreach (DataRow row in rows)
{
errorInfo.Add(" - Row Error: ", row.RowError);
DataColumn[] cols = row.GetColumnsInError();
if ((cols != null) && (cols.Length > 0))
{
foreach (DataColumn col in cols)
{
errorInfo.Add(" - Column: ", col.ColumnName);
errorInfo.Add(" Column Error: ", row.GetColumnError(col));
}
}
}
}
}
return errorInfo;
}