fonix232
fonix232

Reputation: 2195

WPF DataGrid - get items from column

I'm looking for a simple way to retrieve all items in a specific column of a WPF DataGrid. I have both the DataGrid, DataGridColumn and DataGridColumnHeader as a reference, but I can't seem to find a logical way of getting the elements.

Using the Header property of the DataGridColumn is not an option as I'm using a custom Header object in some cases.

Upvotes: 0

Views: 3491

Answers (1)

Bilal Bashir
Bilal Bashir

Reputation: 1493

It is pretty straight forward to do that if you already have an instance of the DataGrid. Here is a simple extension method you can use to get an enumerable of all items in column of DataGrid.

namespace Extensions
{
    public static class DataGridExtension
    {
        public static IEnumerable<FrameworkElement> GetItemsInColumn(this DataGrid dg, int col)
        {
            if (dg.Columns.Count <= col)
                throw new IndexOutOfRangeException("Column " + col + " is out range, the datagrid only contains " + dg.Columns.Count + " columns.");
            foreach (object item in dg.Items)
            {
                yield return dg.Columns[col].GetCellContent(item);
            }
        }
    }
}

Then to call the method you can just do,

dg.GetItemsInColumn(colNumber);

Upvotes: 0

Related Questions