DataGridView列数据到数组 [英] DataGridView Column Data to Array

查看:295
本文介绍了DataGridView列数据到数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以将所有数据从 DataGridView 列传输到 string []数组

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

不幸的是,这是我的代码,无法将 DataGridViewRow 转换为 int

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;
}


推荐答案

您可以通过多种方式方式:

You can do it in various ways:


  • 对循环使用普通的 foreach 只是语法糖,真正的工作总是使用旧的for循环完成。

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

使用 foreach DataGridViewRow.Index 属性设置数组索引。

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

使用 LINQ 创建数组

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!

这篇关于DataGridView列数据到数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆