在 DataGridView 中显示二维数组

Show 2d-array in DataGridView

我有一个二维数组。我想在我的 DataGridView 中打印数组,但它会引发错误:

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

第一个潜在问题是您访问数组索引的方式。可以这样处理。

string[,] a = {
  {"0", "1", "2"},
      {"0", "1", "2"},
      {"0", "1", "2"},
      {"0", "1", "2"},
  };

for (int i = 0; i < a.GetLength(0); i++)
{
    for (int j = 0; j < a.GetLength(1); j++)
    {
        Console.WriteLine(a[i,j]);
    }
}

首先检查您的数组维度长度。显然您的变量高度或宽度之一不正确。

这是使用 Array.GetLength(int dimension)

完成的

第二个问题是如何将项目添加到 datagridview。

例如 2 个元素

dataGridView1.ColumnCount = 2;
var dataArray = new int[] { 3, 4, 4, 5, 6, 7, 8 };
for (int i = 0; i < dataArray.Count; i++)
{
   dataGridView1.Rows.Add(new object[] { i, dataArray[i] });
}

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

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

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