简体   繁体   中英

How do we programatically add data from datagrid to list?

I have the following code, but the list is not fetching the exact values from datagrid.

public List<double[]> ExtractGridData(DataGridView grid)
    {
        int numCols = grid.Columns.Count;
        List<double[]> list = new List<double[]>();

            double[] cellsData = new double[numCols];
            foreach (DataGridViewCell cell in grid.SelectedCells)
            {
                if (cell.Value != null)
                    cellsData[cell.RowIndex] = Convert.ToDouble(cell.Value);
                    list.Add(cellsData);
            }

        return list;
    }

I think all you need to do is move:

double[] cellsData = new double[numCols];

to within the start of your loop. At the moment, your using the same instance of the array every iteration.

try this Code as Extract data from Grid for a Specific column

 public List<double> ExtractGridData(DataGridView grid)
    {
        int numCols = grid.Columns.Count;
        List<double> list = new List<double>();
        int i = 0;
        double[] cellsData = new double[numCols];
        foreach (DataGridViewRow row in grid.SelectedRows)
        {
            if(row.Cells[2].Value != null)
            {
            string value = row.Cells[2].Value.ToString();// third columnn of Grid as            //Example



            list.Add(Convert.ToDouble(value));
            }  


        }


        return list;
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM