更新时间:2023-11-26 11:24:52
您的代码将控件引用视为名称(字符串变量),因此您将获得类型名称 (System.windows.datagridview) 而不是控件的名称.由于模板 DGV 恰好有名称,请使用它:
Your code is treating a control reference as if it were a name (string variable), so you get the Type name (System.windows.datagridview) rather than the name of the control. Since the template DGV happarently has the name, use it:
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 可能需要对名称和索引进行一些转换
Note: Option Strict would likely require some conversions for the name and index
如果 DGV 位于面板或选项卡等容器控件中,您必须找到"该控件,因为它们将位于那个控件的集合中,而不是表单的集合中.而不是 myDGV = CType(Me.Controls(myGridName), DataGridView)
:
If the DGV(s) reside in container controls like Panels or Tabs, you have to "find" the control because they will be in that control's collection, not the Form's. Instead of 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
这通常从一开始就更好,因此您不必在编码时记住表单的布局.
This is usually better from the start so you do not have to remember how the form is laid out when coding.