更新时间:2023-02-26 16:33:19
由于意见所指出的那样,你应该专注于行和单元格。你需要建立你的 DataGridView的
列,然后通过细胞填充每一行的单元格。
您阵的宽度应符合您的DGV列和
高度
来的DGV行。采取以下作为一个简单的例子:
字符串[,]数组twoD =新的字符串[,]
{
{排0 COL 0,0行山口1,0行栏2},
{行1列0,(1,1),行1列2},
{行2列0,行2列1,行2列2},
{排3 COL 0,3排第1栏,第3行第2栏},
};INT高度= twoD.GetLength(0);
INT宽度= twoD.GetLength(1);this.dataGridView1.ColumnCount =宽度;对于(INT R = 0;为r的高度; R ++)
{
一个DataGridViewRow行=新的DataGridViewRow();
row.CreateCells(this.dataGridView1); 对于(INT C = 0; C<宽度; C ++)
{
row.Cells [C]。价值=数组twoD [R,C]。
} this.dataGridView1.Rows.Add(行);
}
I have a 2D array. I want to print the array in my DataGridView
but it throws an error:
[Argument OutOfRangeException was unhandled ]
This is my code
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;
}
}
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.
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);
}