代码之家  ›  专栏  ›  技术社区  ›  minseong

检查所选内容跨越DataGridView的行数

  •  0
  • minseong  · 技术社区  · 6 年前
    DataGridView.SelectedRows
    

    似乎只计算完全选定的行。

    如果我从单个列中选择多个单元格, DataGridView.SelectedRows 似乎总是返回0(如果有多个列)。

    如何获取用户所选范围内的行数?

    2 回复  |  直到 6 年前
        1
  •  1
  •   minseong    6 年前

    我想你必须对它们进行唯一的计数:

    HashSet<int> rowIndexes = new HashSet<int>();
    foreach (DataGridViewCell cell in dgv.SelectedCells) {
      if (!rowIndexes.Contains(cell.RowIndex)) {
        rowIndexes.Add(cell.RowIndex);
      }
    }
    
    selectedRowCount = rowIndexes.Count;
    
        2
  •  0
  •   Ryan Wilson    6 年前

    一种方法是迭代每行的每个单元格,并检查 .Selected 一个单元格的属性,尽管在发布后,我看到了Larstech的答案,它可能更有效,因为它只查看选定的单元格:

    //Variable to hold the selected row count
    int selectedRows = 0;
    //iterate the rows
    for(int x = 0; x < DataGridView.Rows.Count; x++)
    {
       //iterate the cells
       for(int y = 0; y < DataGridView.Rows[x].Cells.Count; y++)
       {
            if(DataGridView.Rows[x].Cells[y] != null)
               if(DataGridView.Rows[x].Cells[y].Selected)
               {
                  //If a cell is selected consider it a selected row and break the inner for
                  selectedRows++;
                  break;
               }
       }
    
    
    }