如何在我的 DataGrid 中获取所选单元格的当前列(C# WPF 应用程序)

Posted

技术标签:

【中文标题】如何在我的 DataGrid 中获取所选单元格的当前列(C# WPF 应用程序)【英文标题】:How to get current column of selected cell in my DataGrid (C# WPF Application) 【发布时间】: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。也许有人有想法?

【问题讨论】:

这能回答你的问题吗? How to find column name with column index in DataGridView? 【参考方案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;

【讨论】:

以上是关于如何在我的 DataGrid 中获取所选单元格的当前列(C# WPF 应用程序)的主要内容,如果未能解决你的问题,请参考以下文章

WPF datagrid按钮列点击如何获取当前行某单元格的值!

WPF的DataGrid中如何获取当前被选定的行的第一个单元格的值?

如何快速按下所选单元格的IndexPath

如何获取与表连接绑定的 Row datagridview selectedItem 的每个单元格的值?

android日历控件怎么获得所选日期的单元格的焦点

以编程方式获取或设置 Datagrid 中的单元格值