0

I have a DataGrid bound to a DataTable which when the program is first started is empty, if the user is to add a value it is written to the appropriate DataTable cell as it should.

However if the user is the remove this value, the DataGrid will not allow it and will not update the DataTable, like so:

enter image description here

I can not seem to find anything online about this and not sure if it is to do with the DataGrid or the DataTable, any help is greatly appreciated! Thanks!

Alfie
  • 297
  • 1
  • 12
  • Here is one solution. https://stackoverflow.com/questions/1156731/how-do-i-get-a-wpf-datagrid-to-save-changes-back-to-the-database I hope this helps – Andrew Greatorex Oct 11 '18 at 10:45
  • Is it because it's trying to set a .NET `null` to the table, but it really wants a `DbNull.Value`? – DonBoitnott Oct 11 '18 at 11:48
  • @DonBoitnott yeah that definitely sounds like a possible cause of the issue, do you know how I could go about assigning `DbNull.Value` to the `DataTable` if the user has entered a .NET `null` value? – Alfie Oct 11 '18 at 13:21
  • You'd probably have to be using a `Converter` on the binding. – DonBoitnott Oct 11 '18 at 13:22

2 Answers2

2

You could handle the AutoGeneratingColumn event and apply a converter to the bindings:

private static readonly ConvertStringToDBNull _converter = new ConvertStringToDBNull();
private void dgDt_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
{
    ((DataGridBoundColumn)e.Column).Binding = new Binding(e.PropertyName) { Converter = _converter };
}

You will find a sample implementation of a converter that converts between string.Empty and DBNull.Value here.

mm8
  • 163,881
  • 10
  • 57
  • 88
0

you have to set your binding for read and write, set the binding Mode=Twoway.

Saber CHETIOUI
  • 50
  • 1
  • 13