【问题标题】:How to get the selected column count in datagrid如何在datagrid中获取选定的列数
【发布时间】:2013-10-24 05:48:49
【问题描述】:

我想要 DataGrid 的选定列的索引。例如,如果我选择第一列,我想要第一列的索引(索引 = 0)。

我在 DataGrid SelectionChanged 事件中尝试过,但我似乎无法获得特定的列索引。如果有人知道怎么做,请帮我提供一些示例代码。

【问题讨论】:

  • 只是需要再澄清一点,你是说想要当前选择的列数吗?
  • 你的意思是当前选中列的索引?

标签: wpf


【解决方案1】:

DataGrid.Items 属性返回一个表示 DataGrid 中的 DataGridItems 的 DataGridItemCollection。

每个 DataGridItem 代表呈现表中的一行。此外,DataGridItem 公开了一个代表编号的 Cells 属性。呈现的表格中的表格单元(换句话说,列)。

// Get the Row Count
int rowCount = myGrid.Items.Count;

// Get the no. of columns in the first row.
int colCount = myGrid.Items[0].Cells.Count;

【讨论】:

  • 你的代码 int colCount = myGrid.Items[0].Cells.Count; .cells 处出现错误。我真正的问题是,如果我单击数据网格中的第一列,我希望列计数为 0,等等我怎么能在选择更改事件中做到这一点
  • 你的意思是选择的索引吗? int selectedIndex = myGrid.SelectedIndex;
  • 不,如果我单击星期一列,我在数据网格中有列星期一到星期五,我想要该列计数或列标题名称。即使我能够获得单击的列标题名称,它也可以对我来说
  • 试试这个:-int index = dataGrid1.SelectedCells[0].Column.DisplayIndex;对象头 = dataGrid1.Columns[index].Header;
  • 嗨,感谢您的帮助,我已经在选择更改事件中尝试了这个,它对我有用,我希望它对其他人有帮助 DataGrid x = (DataGrid)this.FindName("attendancegrid") ; var index = x.CurrentColumn; if (index == null) { return; } else { 列名 = x.CurrentColumn.Header.ToString(); }
【解决方案2】:

我假设您想要选择的任何列的索引。这是我想出的代码:

    List<int> selectedColumnIndexes = new List<int>(dataGrid.SelectedCells.Count);

    for (int i = 0; i < dataGrid.SelectedCells.Count; i++)
    {
        foreach (DataGridColumn column in dataGrid.Columns)
        {
            if (column.DisplayIndex == dataGrid.SelectedCells[i].Column.DisplayIndex) 
            {
                    if (!selectedColumnIndexes.Contains(column.DisplayIndex))
                    {
                        selectedColumnIndexes.Add(column.DisplayIndex);
                    }
            }
        }
    }

因此,您将获得当前所选列的所有索引的列表。 This question 提供了一些很好的线索,说明该往哪个方向前进。

显然,如果您只需要实际选择的列数,那么在 for 循环运行后,该值就是 selectedColumnIndexes.Count。

【讨论】:

    猜你喜欢
    • 2011-07-04
    • 2017-11-22
    • 2017-08-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-24
    • 1970-01-01
    相关资源
    最近更新 更多