DataGridView Column Data to Array

ぃ、小莉子 提交于 2019-12-30 11:21:13

问题


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



来源:https://stackoverflow.com/questions/33605223/datagridview-column-data-to-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!