我有一个二维数组。我想在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;
}
}
发布于 2015-04-15 01:38:40
正如注释所指出的,您应该专注于行和单元格。您需要构建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);
}
发布于 2015-04-15 01:15:16
以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] });
}
发布于 2015-04-15 01:00:06
第一个潜在的问题是如何访问数组索引。可以用这种方式来处理。
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]);
}
}
只需先检查数组的维数长度。显然,您的其中一个变量height或width是不正确的。
这是使用Array.GetLength(int dimension)
完成的
第二个问题是如何向datagridview添加项目。
https://stackoverflow.com/questions/29633018
复制相似问题