6

For WinForms it's:

var value = DataGridView.Rows[0].Cells[0].Value

Is there any way to get it in WPF?

Omid
  • 823
  • 1
  • 11
  • 31
  • 1
    As I tell to every winforms developer I find hittin his head against WPF... forget everything you've learned from winforms, this is a different (times better IMO) framework, and requires a completely different mindset. Take a look at MVVM and get familiar with WPF Binding capabilities – Federico Berasategui Nov 03 '12 at 02:52

2 Answers2

5

I think the best way would be to use the Items property and directly access your data item:

var dataItem = dataGrid.Items[0] as ...;

But You can use this class to get the cell and access the value with the GetValue() method (would be more like your example).

Code taken from here: datagrid get cell index

static class DataGridHelper {
    static public DataGridCell GetCell(DataGrid dg, int row, int column) {
        DataGridRow rowContainer = GetRow(dg, 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
                dg.ScrollIntoView(rowContainer, dg.Columns[column]);
                cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(column);
            }
            return cell;
        }
        return null;
    }

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

    static T GetVisualChild<T>(Visual parent) where T : Visual {
        T child = default(T);
        int numVisuals = VisualTreeHelper.GetChildrenCount(parent);
        for (int i = 0; i < numVisuals; i++) {
            Visual v = (Visual)VisualTreeHelper.GetChild(parent, i);
            child = v as T;
            if (child == null) {
                child = GetVisualChild<T>(v);
            }
            if (child != null) {
                break;
            }
        }
        return child;
    }
}
Community
  • 1
  • 1
dwonisch
  • 5,595
  • 2
  • 30
  • 43
4

Generally, you shouldn't need to do that. In WPF, datagrid is meant to be used with data binding, which means there is an underlying collection or object that has the same value as the cell, so you need to access that collection/object directly. If you are needing to access the cell value, you might need to reconsider your design.

Eren Ersönmez
  • 38,383
  • 7
  • 71
  • 92