在DataGridView中显示2d数组

时间:2015-04-14 16:49:09

标签: c# arrays datagridview

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

  

[参数OutOfRangeException未处理]

这是我的代码

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

3 个答案:

答案 0 :(得分:1)

正如评论所指出的那样,你应该关注行和单元格。您需要构建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);
}

答案 1 :(得分:0)

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

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 :(得分:0)

例如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] });
}