I recently ran into a problem with a large DataSet when I set the EnforceConstraints to true. It gave me the error “Failed to enable constraints. One or more rows contain values violating non-null, unique, or foreign-key constraints.” without any clue as to where to look or what to do. Googling the problem, I came across a blog by Dave Lloyd with a good method to figure out exactly where the error is. The only problem was the example code was Dimmed. Naturally I un-Dimmed the code and put it in a proper C# format. I then encapsulated it into a nice little static function that returns a NameValueCollection loaded with all of the relevant error info. The info returned tells you what table, what row/column, and what the constraint is.
| 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; |
| } |
| |