Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does the DataGrid not update when the ItemsSource is changed?

I have a datagrid in my wpf application and I have a simple problem. I have a generic list and I want to bind this collection to my datagrid data source every time an object is being added to the collection. and I'm not interested to use observable collection.

the point is I'm using the same method somewhere else and that works fine. but this time when i press Add button an object is added and datagrid updates correctly but from the second item added to collection datagrid does not update anymore.

Here is the Code :

 private void btnAddItem_Click(object sender, RoutedEventArgs e)     {         OrderDetailObjects.Add(new OrderDetailObject         {             Price = currentitem.Price.Value,             Quantity = int.Parse(txtQuantity.Text),             Title = currentitem.DisplayName,             TotalPrice = currentitem.Price.Value * int.Parse(txtQuantity.Text)         });          dgOrderDetail.ItemsSource = OrderDetailObjects;         dgOrderDetail.UpdateLayout();     } 

any idea ?

like image 429
Pouyan Avatar asked Aug 14 '11 19:08

Pouyan


People also ask

How do you refresh a data grid?

Use the dataGrid. refresh method. Use the reload() method of your DataGrid's dataSource as shown in the following help topic: cacheEnabled. Create a new instance of a store and assign it to your DataGrid's dataSource.

What is the default event of DataGrid?

By default, the DataGrid control generates columns automatically when you set the ItemsSource property. The type of column that is generated depends on the type of data in the column.

How do I filter DataGrid?

To filter items in a DataGridAdd a handler for the CollectionViewSource. Filter event. In the Filter event handler, define the filtering logic. The filter will be applied every time the view is refreshed.

How do I add a DataGrid toolbox?

Right Click the Toolbox. Select "Choose Items...". In the WPF Components Tab, in the Filter Textbox type DataGrid. From there you can add it to the Toolbox.


1 Answers

The ItemsSource is always the same, a reference to your collection, no change, no update. You could null it out before:

dgOrderDetail.ItemsSource = null; dgOrderDetail.ItemsSource = OrderDetailObjects; 

Alternatively you could also just refresh the Items:

dgOrderDetail.ItemsSource = OrderDetailObjects; //Preferably do this somewhere else, not in the add method. dgOrderDetail.Items.Refresh(); 

I do not think you actually want to call UpdateLayout there...

(Refusing to use an ObservableCollection is not quite a good idea)

like image 102
H.B. Avatar answered Oct 12 '22 15:10

H.B.