How to add new row to datagrid through code

Mar 9, 2009 at 9:20 AM
Edited Mar 9, 2009 at 9:26 AM
Hi,

I am new to suing Datagrid control of WPF toolkit. I have a list collection and i am setting itemsource property of my datagrid to that listcollection.
I have set CanUserAddRows="False" so as to avoid getting extra row in the grid.

I am adding items to the list collection on a click event of button and again setting that listcollection as an item source to datagrid. But new items does not gets added to datagrid. It displays old collection of items only.

I am not sure where am i doing wrong over here. My collection contains old items as well as new item. Then datagrid should display new collection of data.

Please help me out to figure out the issue.
Mar 9, 2009 at 11:30 AM
Hi,

Let me see if I can help.

The fist part sounds good, creating a List and setting it as the ItemsSource of your DataGrid.

So, you are adding new items to you list in code-behind and want the DataGrid, which is a view on this list, to update accordingly. The best way to do this is to use a List collection type that raises events when items are added or removed. ObservableCollection is a good candidate for your needs (See the CollectionChanged event - this is raised when items are added / removed).

So, if you add your objects to an ObsrvableCollection, your DataGrid should update automatically as items are added / removed.

For a more detailed example see the following:

http://www.codeproject.com/KB/WPF/WPFDataGridExamples.aspx#layered

Regards,
Colin E.
--
http://www.scottlogic.co.uk/blog/wpf/ - my WPF blog
http://www.codeproject.com/KB/WPF/WPFDataGridExamples.aspx - WPF DataGrid Practical Examples



Mar 12, 2009 at 6:54 AM
Hi thanks for the reply,

I tried setting datagrid.itemsource =  null and then resetting new collection as itemsource. It worked for me :)

thanks