简体   繁体   中英

How can I get row in datagrid WPF?

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


        }

    }

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.

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 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM