问题
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;
}
回答1:
You can do it in various ways:
Use a normal
for
-loop. Theforeach
is only syntactic sugar, the real work is always done with the good old for-loop.Use
foreach
and theDataGridViewRow.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!
来源:https://stackoverflow.com/questions/33605223/datagridview-column-data-to-array