views:

1943

answers:

1

Hi,

Please help me, Im trying to get the value of Cell[0] from the selected row in a SelectionChangedEvent.

I am only managing to get lots of different Microsoft.Windows.Controls and am hoping im missing something daft.

Hoping I can get some help from here...

    private void datagrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        Microsoft.Windows.Controls.DataGrid _DataGrid = sender as Microsoft.Windows.Controls.DataGrid;
    }

I was hoping it would be something like...

_DataGrid.SelectedCells[0].Value;

However .Value isn't an option....

Many many thanks this has been driving me mad! Dan

+1  A: 

pls, check if code below would work for you:

private void dataGrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    DataGrid dataGrid = sender as DataGrid;
    if (e.AddedItems!=null && e.AddedItems.Count>0)
    {
        // find row for the first selected item
        DataGridRow row = (DataGridRow)dataGrid.ItemContainerGenerator.ContainerFromItem(e.AddedItems[0]);
        if (row != null)
        {
            DataGridCellsPresenter presenter = GetVisualChild<DataGridCellsPresenter>(row);
            // find grid cell object for the cell with index 0
            DataGridCell cell = presenter.ItemContainerGenerator.ContainerFromIndex(0) as DataGridCell;
            if (cell != null)
            {
                Console.WriteLine(((TextBlock)cell.Content).Text);
            }
        }
    }
}

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;
}

hope this helps, regards

serge_gubenko
Works perfect! I can see where and why I was going wrong!Many Thanks Serge!
Dan Bater