How to get current column of selected cell in my DataGrid (C# WPF Application)

1.3k Views Asked by At

i want to filter my DataGrid with a RowFilter. The User should be able to choose his column by selecting a cell. Than he puts some Text in a TextBox and he can filter the DataGrid. I tried some things but they didnt work. Maybe i can get some help here :) I would be happy for every reply. Here is my code and the things i tried:

private void Filter_Click(object sender, RoutedEventArgs e)
        {
            DataView DV1 = DT1.DefaultView;        // DT1 is my DataTable-Object
            // DV1.RowFilter = "Column1 = '" + Filter.Text + "'";   This works fine
            DV1.RowFilter = "'" + DataGrid1.CurrentCell.Column+ "' = '" + Filtern.Text + "'"; // When i try this it doesnt work
            DataGrid1.ItemsSource = DV1;
        }

i tried some other commands: DataGrid1.CurrentCell.Column.DisplayIndex or DataGrid1.CurrentCell.Column.Header or DataGrid1.CurrentColumn but i always get an Error. The Command gives me a 0. Maybe someone has an idea?

3

There are 3 best solutions below

0
Yong Shun On

To get the current column name from DataGridView:

int columnIndex = DataGrid1.CurrentCell.ColumnIndex;
string columnName = DataGrid1.Columns[columnIndex].Name;

Next, your RowFilter was incorrect, the column name should not be enclosed with quote '.

DV1.RowFilter = <<ColumnName>> + " = '" + Filtern.Text + "'";

In the end, your code should be as below:

private void Filter_Click(object sender, RoutedEventArgs e)
{
    DataView DV1 = DT1.DefaultView;
    
    // Get column name
    int columnIndex = DataGrid1.CurrentCell.ColumnIndex;
    string columnName = DataGrid1.Columns[columnIndex].Name;

    DV1.RowFilter = String.Format("{0} = '{1}'", columnName, Filtern.Text); 
    DataGrid1.ItemsSource = DV1;
}

Note: This way filtering will only work for columns with string value.

0
stito550 On

try this:

DataGrid1.SelectedCells[0].ColumnIndex

0 is the first element selected

0
Mario Allw On

Thank you Guys! I got it :)

This is my Code, hope it will help some others:

int columnIndex = DataGrid1.SelectedCells[0].Column.DisplayIndex; 
string columnname = Convert.ToString(DataGrid1.Columns[columnIndex].Header);
string fullcommand = string.Format("{0} = '{1}'", columnname, Filtern.Text);
DataView DV1 = DT1.DefaultView; 
DV1.RowFilter = fullcommand;
DataGrid1.ItemsSource = DV1;