Search code examples
c#wpfdatagrid

How can i get all rows of C# Wpf datagrid?


How to get all DataGridRows in DataGrid? like

foreach (DataGridRow dr in postQueue.Items)
    {
        Console.WriteLine(dr.GetIndex());
    }

of cource wrong, because i need every DataGridRow element, not struct.

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

Throws row was null


Solution

  • why don't you bind your DataGrid to an ObservableCollection?

    XAML :

    <DataGrid ItemsSource="{Binding Path=YourList}" >
    ...
    </DataGrid>
    

    MVVM :

    private ObservableCollection<T> yourList = new ObservableCollection<Hole>();
    public ObservableCollection<T> YourList
    {
        get { return yourList; }
        set
        {
            this.yourList = value;
            NotifyPropertyChanged("YourList");
        }
    }
    

    then to get it just do :

    foreach (T element in this.YourList)
    {
       ...
    }