繁体   English   中英

C#datagridview列成一个数组

[英]C# datagridview column into an array

我正在用c#构建一个程序,并在其中包含了一个datagridview组件。 datagridview具有固定数量的列(2),我想将其保存到两个单独的数组中。 但行数确实发生了变化。 我怎么能这样做?

假设一个名为dataGridView1的DataGridView并且您希望将前两列的内容复制到字符串数组中,您可以执行以下操作:

string[] column0Array = new string[dataGridView1.Rows.Count];
string[] column1Array = new string[dataGridView1.Rows.Count];

int i = 0;
foreach (DataGridViewRow row in dataGridView1.Rows) {
    column0Array[i] = row.Cells[0].Value != null ? row.Cells[0].Value.ToString() : string.Empty;
    column1Array[i] = row.Cells[1].Value != null ? row.Cells[1].Value.ToString() : string.Empty;
    i++;
}

我使用Jay的示例并将其更改为将所有行存储在单个数组中以便于导出。 最后,您可以轻松地使用LogArray [0,0]从单元格0,第0列获取字符串。

        // create array big enough for all the rows and columns in the grid
        string[,] LogArray = new string[dataGridView1.Rows.Count, dataGridView1.Columns.Count];

        int i = 0;
        int x = 0;
        foreach (DataGridViewRow row in dataGridView1.Rows)
        {
            while (x < dataGridView1.Columns.Count)
            {
                LogArray[i, x] = row.Cells[x].Value != null ? row.Cells[x].Value.ToString() : string.Empty;
                x++;
            }

            x = 0;
            i++; //next row
        }

我希望我帮助过这个人,这是我第一次在网上发布任何代码。 此外,我还没有编码,只是重新开始。

试试这个:

ArrayList col1Items = new ArrayList();
ArrayList col2Items = new ArrayList();

foreach(DataGridViewRow dr in dgv_Data.Rows)
{
  col1Items.Add(dr.Cells[0].Value);
  col2Items.Add(dr.Cells[1].Value);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM