在 DataGridView 中显示二维数组 [英] Show 2d-array in DataGridView

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

问题描述

我有一个二维数组.我想在我的 DataGridView 中打印数组,但它抛出一个错误:

I have a 2D array. I want to print the array in my DataGridView but it throws an error:

[参数 OutOfRangeException 未处理]

[Argument OutOfRangeException was unhandled ]

这是我的代码

for (int j = 0; j < height; j++)
{
    for (int i = 0; i < width; i++)
    {
            dataGridView1[i, j].Value = state[i, j].h;    
            //state[i, j].h this is my array 
            dataGridView1[i, j].Style.BackColor pixelcolor[i,j];
            dataGridView1[i, j].Style.ForeColor = Color.Gold;
    }
}

推荐答案

正如评论所指出的,您应该关注行和单元格.您需要构建 DataGridView 列,然后逐个单元格填充每一行.

As comments have pointed out, you should focus on rows and cells. You need to build your DataGridView columns and then populate each row cell by cell.

数组的 width 应对应于 dgv 列,height 应对应于 dgv 行.举个简单的例子:

The width of your array should correspond to your dgv columns and the height to the dgv rows. Take the following as a simple example:

string[,] twoD = new string[,]
{
  {"row 0 col 0", "row 0 col 1", "row 0 col 2"},
  {"row 1 col 0", "row 1 col 1", "row 1 col 2"},
  {"row 2 col 0", "row 2 col 1", "row 2 col 2"},
  {"row 3 col 0", "row 3 col 1", "row 3 col 2"},
};

int height = twoD.GetLength(0);
int width = twoD.GetLength(1);

this.dataGridView1.ColumnCount = width;

for (int r = 0; r < height; r++)
{
  DataGridViewRow row = new DataGridViewRow();
  row.CreateCells(this.dataGridView1);

  for (int c = 0; c < width; c++)
  {
    row.Cells[c].Value = twoD[r, c];
  }

  this.dataGridView1.Rows.Add(row);
}

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

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