【问题标题】:How to get current column of selected cell in my DataGrid (C# WPF Application)如何在我的 DataGrid 中获取所选单元格的当前列(C# WPF 应用程序)
【发布时间】:2021-07-30 22:00:45
【问题描述】:

我想用 RowFilter 过滤我的 DataGrid。用户应该能够通过选择一个单元格来选择他的列。比他把一些文本放在一个文本框中,他可以过滤数据网格。我尝试了一些东西,但它们没有用。也许我可以在这里得到一些帮助 :) 我会很高兴收到每一个回复。这是我的代码和我尝试过的事情:

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

我尝试了其他一些命令:DataGrid1.CurrentCell.Column.DisplayIndex 或 DataGrid1.CurrentCell.Column.Header 或 DataGrid1.CurrentColumn,但我总是收到错误消息。指挥部给了我一个 0。也许有人有想法?

【问题讨论】:

标签: c# wpf datagrid rowfilter


【解决方案1】:

从 DataGridView 中获取当前列名:

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

接下来,您的 RowFilter 不正确,列名不应包含引号 '

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

最后,你的代码应该如下:

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

注意:这种过滤方式仅适用于具有 string 值的列。

【讨论】:

    【解决方案2】:

    试试这个:

    DataGrid1.SelectedCells[0].ColumnIndex

    0 是第一个被选中的元素

    【讨论】:

      【解决方案3】:

      谢谢各位!我明白了:)

      这是我的代码,希望对其他人有所帮助:

      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;
      

      【讨论】:

        猜你喜欢
        • 2014-01-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-12-19
        • 1970-01-01
        • 2013-04-04
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多