从动态UserControls VB.NET调用对象

时间:2011-10-03 12:40:35

标签: vb.net visual-studio-2010

喜欢这些论坛,在VB.NET方面我是初学者并且遇到了一些麻烦。

这是我的代码段

    'decleare variables
    Dim vmcount As Integer
    Dim tabcount As Integer
    Dim userControl As Control
    Dim UserControlName As String

    vmcount = combo_vmcount.SelectedItem

    tabcount = 1

    tab_con_vm.TabPages.Clear()


    While (tabcount <= vmcount)

        Dim tabname As New TabPage

        'Load variables
        userControl = New calc_usercontrol_vm

        tabname.Text = "VM" & tabcount

        tabname.Name = "VM" & tabcount

        UserControlName = "UCVM" & tabcount

        userControl.Name = UserControlName

        'actions
        tab_con_vm.TabPages.Add(tabname)


        tabname.Controls.Add(userControl)

         'next
        tabcount = tabcount + 1


    End While
End Sub

我遇到的麻烦是找到一种能够在动态创建的用户控件中调用对象的方法。我认为列表可能是一个选项,但我很难获得语法/让它工作。想知道是否有人有一些想法或不同的方法..

谢谢你们 理查德

3 个答案:

答案 0 :(得分:1)

如果您知道要使用的标签索引

Dim calc_usercontrol As calc_usercontrol_vm = TabPages(index).userControl

或者,如果您不知道索引,可以使用IndexOfKey方法,其中键是tabcontrol的Name

Dim index as Integer = TabPages.IndexOfKey("TabControlName")

答案 1 :(得分:1)

虽然这很可能不是解决问题的最佳方法,但我最终创建了一个全局数组并构建了用户控件。

' USERCONTROL ARRAY
Public UCVMARRAY(30) As calc_usercontrol_vm






Dim tabcount As Integer

    Dim UCVMARRAYindex As Integer

    Dim userControl As Control 'control variable

    Dim UserControlName As String


    vmcount = combo_vmcount.SelectedItem

    tabcount = 1

    UCVMARRAYindex = 0

    tab_con_vm.TabPages.Clear()


    While (tabcount <= vmcount)

        Dim tabname As New TabPage ' Relook at this to improve the method used. Issue was that new page was not generated on loop.

        'Load variables

        userControl = New calc_usercontrol_vm
        ' loads UC

        tabname.Text = "VM" & tabcount

        tabname.Name = "VM" & tabcount

        UserControlName = "UCVM" & tabcount

        userControl.Name = UserControlName

        UCVMARRAY(UCVMARRAYindex) = userControl 'places it back 

        'actions
        tab_con_vm.TabPages.Add(tabname)

        tabname.Controls.Add(userControl)


        'next
        tabcount = tabcount + 1
        UCVMARRAYindex = UCVMARRAYindex + 1


    End While
End Sub

这是非常基本但我得到了它的工作,上面的答案很可能是一个很好的解决方案,但我对vb.net的了解并不是最好的。

答案 2 :(得分:-1)

调用Page.LoadControl方法,然后将其添加到您的页面,最好是在页面生命周期的Init部分。