2

I would like to get all rows in order to check some rows that are the same in the database , I'm try using many solutions in StackOverlow but any of them work for me :

for (int i = 0; i < dataGrid.Items.Count; i++)
{
    DataGridRow row = (DataGridRow)dataGrid.ItemContainerGenerator
                                               .ContainerFromIndex(i);
}

This code return value cannot be null Exception.

I have tried also this line of code and I'm got the same Exception ( the object currentitem was null ).

var currentItem = myDataGrid.SelectedItem as MyObject;

Complete Code:

  private void UserControl_Loaded(object sender, RoutedEventArgs e)
     {

        grid.ItemsSource = null;
        grid.ItemsSource = work;
        grid.Items.Refresh();

        for (int i = 0; i < grid.Items.Count; i++) // My grid items count equals to 7
        {
          
            DataGridRow row = (DataGridRow)grid.ItemContainerGenerator.ContainerFromIndex(i); // this value was null 
            var currentItem = grid.SelectedItem as object; // this value was null


        }

    }
abdou_dev
  • 805
  • 1
  • 10
  • 28

2 Answers2

0

You could bind the item source of your DataGrid to an ObservableCollection and run a foreach loop over it.

I think that makes things a lot easier.

Tomsen
  • 321
  • 3
  • 12
  • I have already bind the item source to a Array list , can you please tell me what's the difference between ArrayList<> and ObservableCollection? – abdou_dev Nov 24 '20 at 09:23
  • 1
    The ArrayList doesn't raise an event when it changes. The ObservableCollection does this. That means, if you add an item to your ArrayList, your DataGrid won't show that new item automatically. If you add an item to an ObservableCollection, the DataGrid will "refresh" itself. – Tomsen Nov 24 '20 at 09:26
-2

Finally I got it , I fixed the error by using this code :

 for (int i = 0; i < grid.Items.Count; i++)
            {
                GridModel row = (GridModel)grid.Items[i];
            }
// Note : The grid model is a class for the Datagrid ( properties are the same as the columns name of the datagrid 
abdou_dev
  • 805
  • 1
  • 10
  • 28