我试图在datagridview中显示2d数组。我通过Windows窗体将数据生成到2d数组,然后尝试将数据显示到数据网格视图中,但我在线上收到错误 的 row.CreateCells(this.dataGridView1); 提供的行已经属于DataGridView控件。 不确定我做错了什么,如果有人请我把我放在正确的方向 代码如下
iArray = new String[2, 10];
iArray = custDetails.pCustomDetails();
int height = iArray.GetLength(0);
int width = iArray.GetLength(1);
MessageBox.Show(height.ToString());
MessageBox.Show(width.ToString());
this.dataGridView1.ColumnCount = width;
for (int r = 0; r < height; r++)
{
row.CreateCells(this.dataGridView1);
for (int c = 0; c < width; c++)
{
row.Cells[c].Value = iArray[r, c];
}
this.dataGridView1.Rows.Add(row);
}
答案 0 :(得分:1)
这里唯一的问题是你试图在循环中反复添加相同实例的行。
所以这个小修补程序会让你的代码工作
for (int r = 0; r < height; r++)
{
//Fix : create a new instance of row every time
DataGridViewRow row = new DataGridViewRow();
row.CreateCells(this.dataGridView1);
for (int c = 0; c < width; c++)
{
row.Cells[c].Value = iArray[r, c];
}
this.dataGridView1.Rows.Add(row);
}
答案 1 :(得分:0)
我认为这个答案是最好的答案,只需将其重写为C#:
'at first add columns to the dataGridView before insert rows in it
'y = number of the columns which should equal yourArray.getlength(0) - 1
'you can change (col) to any type of column you need
For i = 0 To y
Dim col As New DataGridViewTextBoxColumn
col.DataPropertyName = "PropertyName" & i.ToString
col.HeaderText = i.ToString
col.Name = "colWhateverName" & i.ToString
DataGridView1.Columns.Add(col)
Next
'now you insert the rows
'exampleRow ={yourArray(0,0), yourArray(0,1), ..... ,yourArray(0,y)}
'x = number of rows
For i = 0 To x
Dim aarray As New List(Of String)
For ii = 0 To y
aarray.Add(yourArray(i, ii).ToString)
Next
DataGridView1.Rows.Add(aarray.ToArray)
Next
我做了这样一个应用程序,您可以在这里检查它: https://github.com/ammardab3an/Array-Rotate-90