如何以编程方式将选定的单元格数据移动到DataGrid中的数组

时间:2013-03-16 09:16:08

标签: c# datagrid

这是一个将所有数据从datagrid移动到数组的代码。但我希望只将选定的数据移动到此数组。可以通过鼠标进行选择。

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

1 个答案:

答案 0 :(得分:1)

使用grid.SelectedRows代替grid.Rows

如果grid.SelectedCell设置为CellSelect并且您需要单个单元格值,也可以使用SelectionMode

List<double> cellsData = new List<double>();
foreach (DataGridViewCell cell in grid.SelectedCells)
{
    if( cell.Value != null)
        cellsData.Add(Convert.ToDouble(cell.Value));
}