Isaiah Isaiah - 3 years ago 196
C# Question

DataGridView Column Data to Array

Is it possible to transfer all data from a

Data Grid View
column to
String [ ] array
?

Here is my code so far

Unfortunately , it can't convert Data Grid View Row to Int

foreach (Data Grid View Row dgvrows in dgvDetail.Rows)
{
array[dgvrows] = dgvDetail.Rows[dgvrows].Cell[3].value.ToString().Trim;
}

TaW TaW
Answer Source

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 (DataGridView Row 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!

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download