[英]Unable to fetch number of selected Columns or Rows in DataGridView
我有以下代碼:
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);
我只能得到總單元數,而不能得到總數或選定的行或列數。 可能是什么問題?
如果沒有填充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的大小,即使未選擇該范圍內的所有單元格也是如此。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.