Next Door Engineer
Next Door Engineer

Reputation: 2886

Unable to fetch number of selected Columns or Rows in DataGridView

I have the following piece of code:

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;
    }

I even tried using the following code:

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

I only get the number of total cells, nut not the number or selected rows or columns. What might the problem be?

Upvotes: 0

Views: 823

Answers (1)

Joachim Isaksson
Joachim Isaksson

Reputation: 180987

If you're not getting SelectedRows populated, you may not have the correct SelectionMode set (been there, done that);

The SelectionMode property must be set to FullRowSelect or RowHeaderSelect for the SelectedRows property to be populated with selected rows.

If you need column and row selection, not just entire rows or columns, you're better off using SelectedCells which is always populated whichever SelectionMode is set.

EDIT: If you need the number of selected rows and columns, this may help (untested since I don't have a WIndows box handy)

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;
}

Note that if you select a single cell at (1,1) and another cell at (7,7), you'll get size 7x7, even if not all cells in the range are selected.

Upvotes: 1

Related Questions