DataGridView Column Data to Array

后端 未结 1 1782
情话喂你
情话喂你 2021-01-14 23:54

Is it possible to transfer all data from a DataGridView column to string[] array ?

Here is my code so far, unfortunately, it can\'t convert

相关标签:
1条回答
  • 2021-01-15 00:45

    You can do it in various ways:

    • Use a normal for-loop. The foreach is only syntactic sugar, the real work is always done with the good old for-loop.

    • Use foreach and the DataGridViewRow.Index property to set the array index.

    • Use LINQ to create the array


    for (int i = 0; i < dgvDetail.Rows.Count; i++)
    {
        array[i] = dgvDetail.Rows[i].Cells[3].Value.ToString().Trim();
    }   
    
    
    foreach (DataGridViewRow row in dgvDetail.Rows) 
    {
        array[row.Index] = row.Cell[3].Value.ToString().Trim();
    }
    
    
    var array = dgvDetail.Rows
        .Cast<DataGridViewRow>()
        .Select(x => x.Cells[3].Value.ToString().Trim())
        .ToArray();
    

    Note that in both loops you need to initialize the array first!

    0 讨论(0)
提交回复
热议问题