【问题标题】:Unable to fetch number of selected Columns or Rows in DataGridView无法获取 DataGridView 中选定列或行的数量
【发布时间】:2026-01-23 02:10:01
【问题描述】:

我有以下代码:

public double[] ExtractGridData(DataGridView grid)
    {
        numCells = grid.SelectedCells.Count;
        numberOfRows = grid.SelectedRows.Count;
        numberOfColumns = grid.SelectedColumns.Count;

        double[] cellsData = new double[numCells];

            foreach (DataGridViewCell cell in grid.SelectedCells)
            {
                if (cell.Value != null)
                    cellsData[cell.RowIndex] = Convert.ToDouble(cell.Value);
            }
            MessageBox.Show(numberOfRows.ToString());
        return cellsData;
    }

我什至尝试使用以下代码:

Int32 selectedRowCount = grid.Rows.GetRowCount(DataGridViewElementStates.Selected);

我只得到总单元格的数量,而不是数量或选定的行或列。可能是什么问题?

【问题讨论】:

    标签: c# .net datagrid datagridview


    【解决方案1】:

    如果您没有得到 SelectedRows 填充,您可能没有设置正确的 SelectionMode(去过那里,做过);

    必须将 SelectionMode 属性设置为 FullRowSelect 或 RowHeaderSelect 才能使用选定的行填充 SelectedRows 属性。

    如果您需要选择列和行,而不仅仅是整个行或列,最好使用SelectedCells,无论设置哪个 SelectionMode 都会填充。

    编辑:如果您需要选定的行数和列数,这可能会有所帮助(未经测试,因为我手边没有 WIndows 框)

    int xsize = 0, ysize = 0;
    var b = a.SelectedCells.Cast<DataGridViewCell>().ToList();
    if (b.Any())
    {
        ysize = b.Max(x => x.RowIndex) - b.Min(x => x.RowIndex) + 1;
        xsize = b.Max(x => x.ColumnIndex) - b.Min(x => x.ColumnIndex) + 1;
    }
    

    请注意,如果您在 (1,1) 处选择一个单元格并在 (7,7) 处选择另一个单元格,即使没有选择该范围内的所有单元格,您也会得到 7x7 的大小。

    【讨论】:

    • grid.SelectionMode 可以使用the DataGridViewSelectionMode enumerable 中的任何值进行设置,但如果您对已有的选择模式感到满意并且它不是上述之一,请查看我在SelectedCells 上的说明。
    • SelectedCells 将给出整个单元格数。但是有没有办法只获取选定的行数和列数?
    • @VR17 查看我的更新。未经测试,但应该是您正在寻找的。​​span>