2

这是一个将所有数据从数据网格移动到数组的代码。但我只想将选定的数据移动到这个数组中。选择可以通过鼠标完成。

public List<double[]> ExtractGridData(DataGridView grid)
    {
        int numCols = grid.Columns.Count;
        List<double[]> list = new List<double[]>();
        foreach (DataGridViewRow row in grid.Rows)
        {
            if (row.IsNewRow) // skip the new row
                continue;
            double[] cellsData = new double[numCols];
            foreach (DataGridViewCell cell in row.Cells)
                if (cell.Value != null)
                    cellsData[cell.ColumnIndex] = Convert.ToDouble(cell.Value);
            list.Add(cellsData);
        }

        return list;
    }
4

1 回答 1

1

Use grid.SelectedRows instead of grid.Rows.

You can also use grid.SelectedCell if the SelectionMode is set to CellSelect and you need individual cell values:

List<double> cellsData = new List<double>();
foreach (DataGridViewCell cell in grid.SelectedCells)
{
    if( cell.Value != null)
        cellsData.Add(Convert.ToDouble(cell.Value));
}
于 2013-03-16T09:20:39.700 回答