3

Possible Duplicate:
Select DataGridCell from DataGrid

I have a datagrid in WPF with some columns and rows. when I click on a row I want to get the first column of the selected row. How can I do it? can I use LINQ for that? thanx

Community
  • 1
  • 1
Payam Sh
  • 31
  • 1
  • 1
  • 2

2 Answers2

0

You can simply use this extension method-

public static DataGridRow GetSelectedRow(this DataGrid grid)
{
    return (DataGridRow)grid.ItemContainerGenerator.ContainerFromItem(grid.SelectedItem);
}

and you can get a cell of a DataGrid by an existing row and column id(0 in your case):

public static DataGridCell GetCell(this DataGrid grid, DataGridRow row, int column)
{
    if (row != null)
    {
        DataGridCellsPresenter presenter = GetVisualChild<DataGridCellsPresenter>(row);

        if (presenter == null)
        {
            grid.ScrollIntoView(row, grid.Columns[column]);
            presenter = GetVisualChild<DataGridCellsPresenter>(row);
        }

        DataGridCell cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(column);
        return cell;
    }
    return null;
}

Check this link for details - Get WPF DataGrid row and cell

akjoshi
  • 15,374
  • 13
  • 103
  • 121
0
var firstSelectedCellContent = this.dataGrid.Columns[0].GetCellContent(this.dataGrid.SelectedItem);
var firstSelectedCell = firstSelectedCellContent != null ? firstSelectedCellContent.Parent as DataGridCell : null;

This way you can get FrameworkElement that is a content of a DataGridCell and a DataGridCell itself.

Note that if DataGrid has EnableColumnVirtualization = True, then you might get null values from the code above.

To get the actual value from a data source, for a specific DataGridCell, is a little more complicated. There is no general way to do this, because DataGridCell can be constituted from multiple values (properties) from the backing data source, so you are going to need to handle this for a specific DataGridColumn.

akjoshi
  • 15,374
  • 13
  • 103
  • 121
Stipo
  • 4,566
  • 1
  • 21
  • 37