0

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?

Mario Allw
  • 13
  • 5
  • Does this answer your question? [How to find column name with column index in DataGridView?](https://stackoverflow.com/questions/3819240/how-to-find-column-name-with-column-index-in-datagridview) – Yong Shun May 09 '21 at 05:34

3 Answers3

0

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.

Yong Shun
  • 35,286
  • 4
  • 24
  • 46
0

try this:

DataGrid1.SelectedCells[0].ColumnIndex

0 is the first element selected

stito550
  • 16
  • 1
0

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;
Mario Allw
  • 13
  • 5