2

Here is a code that moves all the data from datagrid to the array. But I want only selected data to be moved to this array. Selection may be done by mouse.

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 Answer 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));
}
Sign up to request clarification or add additional context in comments.

8 Comments

How do i set SelectionMode to CellSelect?
@user2049436 What do you mean "didn't work"? What happened exactly? In design mode, select your grid, bring the Porperties window (press F4), change SelectionMode to CellSelect. Or in code: grid.SelectionMode = DataGridViewSelectionMode.CellSelect;.
Am getting an exception even after selecting the rows.
In the code: "cellsData does not exist in current context" is the error.
@user2049436 Please look closely at the code in the answer. cellsData is defined by me, on the line before the foreach loop. What is the exception? Please read some books and learn how to really program in C# and Winforms.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.