JWL
JWL

Reputation: 14191

How to View, Edit and Update a Database Table with WPF's DataGrid?

am a newbie in the WPF and more so the WPF Datagrid arena. Am so used to working with the cousin -- DatagridView from Windows Forms, but it's my first time working with WPF's Datagrid Control, and am having a very hard time!

I have created a dataset using the in-built datasource wizard in Vidual Studio 2010. After creating this dataset, I used another in-built feature that allows me to auto-generate a datagrid that is pre-bound to this a table in the dataset, so I can just drop it onto the window.

Now, all that is done nicely, til I come to the part where I need to have the user edit the contents of the datagrid, and via a callback, have the new / updated data committed to the underlying table in the database.

I've tried searching around, but most articles are out-dated, and some don't hit the problem in ways that make sense to a newbie like me.

One source says:

DataGrid checks for IEditableCollectionView’s CanAddNew, CanCancelEdit, and CanRemove properties before executing the EditItem, CancelEdit, or CommitEdit methods. So if editing appears to not work for some reason, be sure to check that it is able to edit.

from an MSDN source, but the Auto-generation feature of Visual Studio 11 gives me this for the data-binding source

<Window.Resources>
    <my:crimexDataSet x:Key="crimexDataSet"  />
    <CollectionViewSource x:Key="datapoolViewSource" Source="{Binding Path=datapool, Source={StaticResource crimexDataSet}}" />
</Window.Resources>

So, how do I move from this to an IEditableCollectionView kind datasource, so I can have editing enabled? Thanks in advance...

Upvotes: 2

Views: 2103

Answers (1)

Rune Jacobsen
Rune Jacobsen

Reputation: 10081

If this isn't an application with a short lifetime, I would save myself a lot of pain and learn about the MVVM (Model-View-ViewModel) pattern. It is a very common pattern in the WPF and Silverlight worlds.

Basically, you would make a class specifically designed to be the data source for the grid, and perhaps other data you would need in your window.

For this particular need, you would probably use an ObservableCollection as the type of the property bound to the grid.

There is a lot of information on MVVM here at StackOverflow, to be found on Google, and in books. If you grok the pattern, it can really make the UI development experience a lot less painful.

Upvotes: 1

Related Questions