D J
D J

Reputation: 243

DataTable.GetChanges(DataRowState.Added) fails with null values

C#, WinForms, DataGridView, DataTable. My form allows the user to enter data into a new row (as opposed to, say, popping up a single record view of the record). When the user clicks my Save button, the click event looks like this:

DataTable dtAddRows = this.SomeFictitiouslyNamedDataSet.SomeFictitiouslyNamedDataTable.GetChanges(DataRowState.Added);

My assumption is that calling GetChanges with that enum is going to get me a set of the rows that were added to the grid at run time. However, it errors out because 1 of the columns "Last_Updated_DT" (which must be displayed and readonly) is a date column that will be populated when we write to the datatable. However, the DataSet has a rule that this column cannot be null.

The problem is, I get an error indicating that the Last_Updated_DT column is actually null (surprise surprise). Its a new row, and the column is readonly in the grid, so of course it is null.

How do I get around this error or stuff a value in that (or those) rows for that column before I actually try to get the added rows?

Upvotes: 1

Views: 918

Answers (1)

D J
D J

Reputation: 243

For the sake of posterity:

private void myGrid_DefaultValuesNeeded(object sender, DataGridViewRowEventArgs e)
{
    e.Row.Cells["MyColumnNameGridViewTextBoxColumn1"].Value = String.Empty;
}

Adding that event to my code fixed my issue. I set the value to String.Empty so it wouldnt put a date/time value in the column until after the Save was clicked.

Then, in the Save_Click event, I get the added rows with this code:

DataTable dtAddedRows = this.dsMyDataSet.MyDataTable.GetChanges(DataRowState.Added);

Then, in the TableAdapter.Insert parameter list, I added DateTime.Now for the date parameter.

Eventually call MyTableAdapter.Update method using the DataSet overload.

All fixed.

Hat tip to @KiNeTiC for providing the necessary guidance.

Upvotes: 1

Related Questions