[英]c# 2d array in to datagrid view
我正在嘗試在datagridview中顯示2d數組。 我通過Windows窗體將數據生成到2d數組中,然后嘗試將該數據顯示到datagrid視圖中,但是在行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);
}
唯一的問題是,您試圖一次又一次地循環添加同一行實例 。
因此,此小修正將使您的代碼正常工作
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);
}
我認為此答案是您可以找到的最佳答案,只需將其重寫為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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.