在DataGridView中显示2d数组

我有一个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; } } 

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

数组的width应与dgv列和dgv行的height相对应。 以下是一个简单的例子:

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

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

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

只需先检查arrays尺寸长度。 显然,你的一个变量高度或宽度是不正确的。

这是使用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] }); }