views:

23

answers:

1

Can anyone point me to a very simple example(C#4.0) of a WPF Datagrid thats bound to a SQL table. I'd really like the simplist example possible. I want to be able to add, edit and delete rows. Thanks.

A: 

If you are looking for something so simplistic that all the add/edit/delete commands are generated/done for you, then I think you are out of luck, because as far as I know, you have to code all that your self. Unless you perhaps use ADO.NET and DataSets, because Visual Studio does have wizards that will generate update/insert/delete/select statements for datasets...

I myself use LINQ to SQL for all my SQL related stuff, including showing data in a DataGrid. It's fairly simple, although I did find the DataGrid (v1, included in .NET Framework 4) to be a half baked piece of cr*p riddled with bugs and quirks. But in general the steps required to edit some SQL table data would be:

1) Create a "LINQ to SQL Classes" file with your SQL schema;

2) Load data into your datagrid, eg. - this.DataGrid1.ItemsSource = new BindingList((from c in Customers select c).ToList());

3) For the bindings in the DataGrid's columns, set NotifyOnSourceUpdated to true and then handle the DataGrid's SourceUpdated event. In the event handler you can insert the updated item (obtainable via event handler arguments -> BindingOperations.GetBindingExpression(e.TargetObject, e.Property).DataItem) into a pre-determined HashSet (hashsets contain only unique values, so if multiple cells are updated in the same row, there will still only be unique items in your hashset).

4) In your save button click event handler you can iterate through the HashSet and push the modified data back to the SQL database, again via LINQ. If the primary key column is int you can check for new rows via item.Id == 0 (item is an enumerated object from the hashset) and then insert the item into the table. Otherwise if Id != 0, select an object from the database with the specified Id and update it's properties with the values of the enumerated item.

Marko