Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find datagrid column name when a cell is clicked in datagrid

Tags:

wpf

datagrid

I wanted to find the datagrid column header when a cell is clicked.. i used the following code

private void grid1_PreviewMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
  {    
    DependencyObject dep = (DependencyObject)e.OriginalSource;
       while ((dep != null) &&     
            !(dep is DataGridColumnHeader))
    {
        dep = VisualTreeHelper.GetParent(dep);
    }

    if (dep == null)
        return;

    if (dep is DataGridColumnHeader)
    {
        DataGridColumnHeader columnHeader = dep as DataGridColumnHeader;

        if (columnHeader.ToString() == "Adv Comments")
        {
        MessageBox.Show(columnHeader.Column.Header.ToString());

        }
    }
    if (dep is DataGridCell)
        {
            DataGridCell cell = dep as DataGridCell;

        }
     }

But the column header is not a direct parent for the datagrid cell so its not able to find it. is there anyother way out??

like image 856
prem Avatar asked Oct 18 '10 18:10

prem


1 Answers

The original source being clicked isn't really connected to the so called item container (see the DataGrid.ItemContainerGenerator) so trying to work yourself up the hiearchy, although a nice idea won't get you to far.

For a quite silly simple solution you could use the knowledge of it being only one cell being clicked and thus using that clicked cell to retrieve the column, as this:

private void DataGrid_PreviewMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
    // First check so that we´ve only got one clicked cell
    if(myGrid.SelectedCells.Count != 1)
        return;

    // Then fetch the column header
    string selectedColumnHeader = (string)myGrid.SelectedCells[0].Column.Header;
}

This perhaps ain´t the prettiest of solutions but simple is king.

Hope it helps!

like image 166
Almund Avatar answered Nov 15 '22 07:11

Almund