2014-06-06 166 views
-1

我正在處理用戶權限。我想加載使用下面的代碼檢查的網格項目。將datagridview名稱存儲在變量中

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

您的代碼正在處理一個控件引用,就好像它是一個名稱(字符串變量),因此您可以獲取類型名稱(System.windows.datagridview)而不是控件的名稱。因爲模板DGV happarently具有名稱,使用它:

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 

注:選項嚴格可能會需要的名稱和索引

如果DGV(一個或多個)駐留在容器控件同樣的面板或部分轉換標籤,你必須「找到」控件,因爲它們將在控件的集合中,而不是Form的。取而代之的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 

這通常是從一開始就更好,所以你不必記住的形式是如何編碼時佈局。

+0

錯誤行myDGV = CType(Me.Controls(myGridName),DataGridView) –

+0

** which ** error?通常應該可以正常工作。修改了選項卡或面板控件中DGV情況的答案,但這不會導致該行上的錯誤 – Plutonix

相關問題