我正在处理用户权限。我想使用以下代码加载检查的网格项。
Dim l As Integer = 0, vrGridName As New DataGridView, vrGridItemIndex As Integer
taSaveTemplates.Connection.ConnectionString += ";password=" & vrSAPWD
Me.taSaveTemplates.Fill(Me.DsSaveTemplates.tblTemplates, lstTemplateID.Text)
'Load Grids according to data saved
Do While DsSaveTemplates.tblTemplates.Rows.Count > l
vrGridName.Name = DsSaveTemplates.tblTemplates.Rows(l).Item("GridName")
vrGridItemIndex = DsSaveTemplates.tblTemplates.Rows(l).Item("GridItemIndex")
vrGridName.Item(0, vrGridItemIndex).Value = True
l = l + 1
Loop
vrGridName存储从DB中选择的网格名称,vrGridItemIndex存储需要检查的项目。
问题是,当我运行代码时,它说Index是我们的范围。 我已经检查过,vrGridName不存储网格名称而是存储 System.windows.datagridview
请指教。 感谢
答案 0 :(得分:0)
您的代码将控件引用视为名称(字符串变量),因此您获取类型名称(System.windows.datagridview)而不是控件的名称。由于模板DGV非常具有名称,请使用它:
Dim myGridName As String ' name is a String, not DGV
Dim myGridItemIndex As Integer
Dim myDGV As DataGridView ' no NEW - not creating a new one
' just a reference var
'...
' this is now a For/Each loop
For Each row As DataGridViewRow in DsSaveTemplates.tblTemplates.Rows
myGridName = row.Cell("GridName")
myGridItemIndex = row.Cell("GridItemIndex")
' assuming this code is in a Form:
' get a reference to the control
myDGV = CType(Me.Controls(myGridName), DataGridView)
' talk to it like a DGV:
myDGV.Item(0, myGridItemIndex).Value = True
Next
注意:Option Strict可能需要对名称和索引进行一些转换
如果DGV位于容器控件(如面板或选项卡)中,则必须“找到”控件,因为它们将位于那个控件的集合中,而不是表单中。而不是myDGV = CType(Me.Controls(myGridName), DataGridView)
:
' have the form search for the ctl by name
' the TRUE param tells it to search child controls like panels
Dim tmpArry = Me.Controls.Find(myGridName, True)
' test for a return
If tmpArry.Length > 0 Then
' tmpArry will be Type Control, so cast it
myDGV = CType(tmpArry(0), DataGridView)
End If
这通常从一开始就更好,所以你不必记住编码时表格的布局。