所以我的情况是我想从数据库中的两个字段填充一个二维数组。
我在为数组分配数据库字段值时遇到问题
第二个是在数据网格中显示数组,我已经编码了 dgv2.Datasource = myArray 但它仍然返回错误消息。
这是我的代码:
Dim msql As String = "select item_id from detail"
Dim arayT(,) As String
CMD = New MySqlCommand(msql, conn.konek)
Try
Dim res= CMD.ExecuteReader()
While res.Read()
For i As Integer = 0 To x - 1
For j = 0 To y - 1
arayT(i, j) = res.GetString("item_id")
Next j
Next i
End While
Catch ex As Exception
MessageBox.Show("ERROR")
End Try
dgv2.DataSource = arayT
所以我的问题是
首先,如何将数据库中的记录列作为值分配到我的二维数组中? (我仍然不确定我的编码是否正确)
其次,如何将二维数组查看到数据网格中,我的意思是将二维数组绑定到数据网格中
我的一些请求...请不要要求我使用列表或使用 LINQ,因为我对它们还不太熟悉。
i have done some fix in my code but it didn't worked nicely..here is my latest screenshot
当您将二维数组设置为 datagridview 的数据源时,您会收到什么错误消息?那么,如果数据源命令给您带来错误,您可以循环并将值分配给 datagridview。
'Ensure that the required number of rows are available
If DataGridView.Rows.Count < some2darray.GetUpperBound(0) Then
DataGridView.Rows.Add((some2darray.GetUpperBound(0) + 1) - DataGridView.Rows.Count)
End If
'Also ensure that the required number of columns are available
'Fill up the datagridview with the data from the 2D array
For x = 0 to some2darray.GetUpperBound(0)
For y = 0 to some2darray.GetUpperBound(1)
DataGridView.Item(y, x).Value = some2darray(x, y)
Next
Next
如果您的 2Darray 中没有参考点并且必须从其他源获取其值,则使用此代码ReDim Preserve some2darray(x, y)
e.g.
For x = 0 to rowcountofthesource
For y = 0 to columncountofthesource
ReDim Preserve some2darray(x, y)
'Code here
DataGridView.Item(y, x).Value = some2darray(x, y)
Next
Next
如果您的二维数组一次性从另一个源获取所有数据。然后 ReDim 将您的 2d 数组保留到该源的总行数和列数,例如ReDim Preserve some2darray(totalrowsofthesourcehere, totalcolumnsofthesourcehere)
并在循环外键入它,因为您不需要一次又一次地执行它。如果您的数组在使用前为空并且不包含任何数据,那么您不需要使用ReDim Preserve
,只需使用ReDim some2darray(int, int)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)