Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/256.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 检查所选内容跨越DataGridView的行数_C#_Winforms_Datagridview - Fatal编程技术网

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

C# 检查所选内容跨越DataGridView的行数,c#,winforms,datagridview,C#,Winforms,Datagridview,似乎只对完全选中的行进行计数 如果我从单个列中选择多个单元格,DataGridView.SelectedRows似乎总是返回0(如果有多个列) 如何获得用户选择范围内的行数?我想您必须对它们进行唯一计数: DataGridView.SelectedRows HashSet行索引=新HashSet(); foreach(dgv中的DataGridViewCell单元格。SelectedCells){ 如果(!rowIndexes.Contains(cell.RowIndex)){ 添加(cell

似乎只对完全选中的行进行计数

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


如何获得用户选择范围内的行数?

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

DataGridView.SelectedRows
HashSet行索引=新HashSet();
foreach(dgv中的DataGridViewCell单元格。SelectedCells){
如果(!rowIndexes.Contains(cell.RowIndex)){
添加(cell.RowIndex);
}
}
selectedRowCount=rowIndexes.Count;

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

HashSet<int> rowIndexes = new HashSet<int>();
foreach (DataGridViewCell cell in dgv.SelectedCells) {
  if (!rowIndexes.Contains(cell.RowIndex)) {
    rowIndexes.Add(cell.RowIndex);
  }
}

selectedRowCount = rowIndexes.Count;
//用于保存所选行计数的变量
int selectedRows=0;
//迭代行
对于(int x=0;x
//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;
           }
   }


}