2

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 DataGridViewRow to int

foreach (DataGridViewRow dgvrows in dgvDetail.Rows)
{
   array[dgvrows] = dgvDetail.Rows[dgvrows].Cell[3].value.ToString().Trim;
}
2

1 Answer 1

4

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.Cells[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!

Sign up to request clarification or add additional context in comments.

1 Comment

row.Cell => row.Cells

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.