Get all cells in datagrid

2019-03-01 14:37发布

Is there a way to get an iteratable collection of all the cells in a DataGrid regardless of whether they are selected or not

3条回答
闹够了就滚
2楼-- · 2019-03-01 14:43

For the sake of convenience (not necessarily performance), you can populate your data (including all cells from all column and rows) from your DataGrid to a single DataTable, which provides functions to help manipulate your data such as iteration, filtering, sorting etc.

// Populate a DataGrid to a DataTable
DataTable dt; 
DataView dv = (DataView) myDataGrid.DataSource;
dt = dv.Table.DataSet.Tables[0];

You can subsequently convert any of a specific column to a collection or list using generics in as short as one line of code. See how-do-you-convert-a-datatable-into-a-generic-list:

List<DataRow> myList = dt.Rows.Cast<DataRow>().ToList();

It saves you from writing loops.

查看更多
闹够了就滚
3楼-- · 2019-03-01 14:58

If you mean DataGridCells you could use Vincent Sibals helper functions to iterate over all rows DataGrid.Items and columns DataGrid.Columns.

public DataGridCell GetCell(int row, int column)
{
    DataGridRow rowContainer = GetRow(row);

    if (rowContainer != null)
    {
        DataGridCellsPresenter presenter = GetVisualChild<DataGridCellsPresenter>(rowContainer);

        // try to get the cell but it may possibly be virtualized
        DataGridCell cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(column);
        if (cell == null)
        {
            // now try to bring into view and retreive the cell
            DataGrid_Standard.ScrollIntoView(rowContainer, DataGrid_Standard.Columns[column]);
            cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(column);
        }
        return cell;
    }
    return null;
}

public DataGridRow GetRow(int index)
{
    DataGridRow row = (DataGridRow)DataGrid_Standard.ItemContainerGenerator.ContainerFromIndex(index);
    if (row == null)
    {
        // may be virtualized, bring into view and try again
        DataGrid_Standard.ScrollIntoView(DataGrid_Standard.Items[index]);
        row = (DataGridRow)DataGrid_Standard.ItemContainerGenerator.ContainerFromIndex(index);
    }
    return row;
}

Edit

If grid is your DataGrid you get a list of all DataGridCells like this:

List<DataGridCell> allCellList = new List<DataGridCell>();

for (int i = 0; i < grid.Items.Count; i++)
{
    for (int j = 0; j < grid.Columns.Count; j++)
    {
        allCellList.Add(grid.GetCell(i, j));
    }
}
查看更多
不美不萌又怎样
4楼-- · 2019-03-01 15:01

To fix the error thrown by the line...

    DataGridCellsPresenter presenter = GetVisualChild<DataGridCellsPresenter> 
        (rowContainer);

Add this routine:

private T GetVisualChild<T>(DataGridRow rowContainer)
    {
        throw new NotImplementedException();
    }
查看更多
登录 后发表回答