tags:

views:

41

answers:

3

How Can Determine Selected Cell's Value In DataGrid? (WPF)

my data grid have 9 coloums and 5 rows and i want to know value of clicked row[0]'s value.

i used this code in windows form

    private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
    {
        var a= dataGridView1[e.ColumnIndex, e.RowIndex].Value;
    }

but i don't know equivalent code in wpf

+1  A: 

Determining a selected cell's value is more of a WinForms thing. WPF is designed to work differently; your UI is meant to be separated from logic. The DataGrid thus becomes an instrument for presentation, not something to be poked and prodded for values.

Instead, with WPF, you want to deal with the objects you have bound to the grid themselves, independent of how they are displayed. Forget the grid - just find the object that is currently "selected" by the user out of a list of bound objects.

The SelectedItem is a property on the grid itself and thanks to WPF's superior binding mechanisms, you can bind this value to a property on a ViewModel via XAML:

ItemsSource="{Binding Orders, Mode=OneWay}" 
SelectedItem="{Binding SelectedOrder, Mode=TwoWay}"

When the user selects an item in the grid, the two-way binding will update the SelectedItem property on the ViewModel with the value of that object in that row.

In that way, you don't even have to deal with the knowledge of the grid or the UI.

I hope that makes sense. I know it's a different approach and a different way of thinking coming from WinForms.

Chris Holmes
This one is great solution :)
Avatar
i know nothing about data binding:(
Shahab
A: 

You should use DataGrid_SelectedCellsChanged event.

    private void dataGrid_SelectedCellsChanged(object sender, SelectedCellsChangedEventArgs e)
    {
        foreach (var item in e.AddedCells)
        {
            var col = item.Column as DataGridColumn;
            var fc = col.GetCellContent(item.Item);

            if (fc is CheckBox)
            {
                Debug.WriteLine("Values" + (fc as CheckBox).IsChecked);
            }
            else if(fc is TextBlock)
            {
                Debug.WriteLine("Values" + (fc as TextBlock).Text);
            }
            //// Like this for all available types of cells
        }
    }

HTH

Avatar
THX a lot Avatar. i want just value of datagrid [selectedrow][first colomn]! i mean that if i clicked on the [3rd row,5th col] it gives me [3rd row, first col]
Shahab
A: 
    private void dataGrid1_SelectedCellsChanged(object sender, SelectedCellsChangedEventArgs e)
    {
        var item = e.AddedCells[0];
        {
            var col = item.Column as DataGridColumn;
            var fc = col.GetCellContent(item.Item);

            if (fc is CheckBox)
            {

            }
            else if (fc is TextBlock && col.DisplayIndex == 0)
            {
                textBlock1.Text = (fc as TextBlock).Text;
            }

        }
    }
Shahab