【问题标题】:Trying to add UserControl to a TabPage inside of another TabPage get NullReferenceException尝试将 UserControl 添加到另一个 TabPage 内的 TabPage 得到 NullReferenceException
【发布时间】:2014-04-04 14:30:52
【问题描述】:

我有一个 UserControl 并希望将它添加到另一个 TabPage 内的 TabPage 但得到 NullReferenceException。

我的代码

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

    Dim MyControl As New TimerPanel
    Dim Ubicacion As Point
    Ubicacion.X = 274
    Ubicacion.Y = 100
    With MyControl
        .Name = "Timer0"
        .NombreTimerTxt.Text = "Timer GPS"
        .TimerBox.Text = "Timer 00"
        .Parent = Me '.TabControl3.TabPages("Timers")
        .Location = Ubicacion
        .Visible = True

    End With

    Me.TabControl3.TabPages("Timers").Controls.Add(MyControl) 'Error here

    'Me.TabControl1.TabPages("Timers").Controls("Timer0").Location = Ubicacion
End Sub

IDE 说我必须使用“New”这个词来声明它,但我已经在第一行代码中做到了。

另一件事,如果我迭代此代码更改名称和坐标,我将获得独立的控件,或者当我更改一个时都做同样的事情?

我的表单如下所示。

【问题讨论】:

  • 您可能没有名为“Timers”的 TabPage。
  • 没错,现在我将 TabName 更改为“Timers”,但结果相同。 :(
  • 然后试试Timers.Controls.Add(MyControl)。您的报价:wish to add it to a TabPage Inside another TabPage 不准确。 TabPage 不能位于另一个 TabPage 内。也许你的意思是 TabControl?不确定。
  • 添加一张图片,让您了解我在 tabPage 中的标签页的含义。正确的顺序是 TabControl->MainTabPage->TabControl->SubTabPage
  • 当你尝试我的建议时会发生什么:Timers.Controls.Add(MyControl)?

标签: vb.net user-controls add vb.net-2010 tabpage


【解决方案1】:

感谢 LarsTech,我解决了这个问题,并使用以下代码向我的 TabPage 添加了几个用户控件

    Dim X As Integer = 4
    Dim Y As Integer = 0

    For XTimer As Integer = 0 To 15
        Dim MyControl As New TimerPanel
        Dim Ubicacion As Point
        Ubicacion.X = X
        Ubicacion.Y = Y
        With MyControl
            .Name = "Timer" & XTimer.ToString
            .NombreTimerTxt.Text = "Timer GPS"
            .TimerBox.Text = "Timer " & XTimer.ToString
            .Parent = Me
            .Location = Ubicacion
            .Visible = True
        End With
        TimersTab.Controls.Add(MyControl)
        Y += 51

        If XTimer = 9 Then 'Start column 2
            X = 344
            Y = 0
        End If
    Next

我希望有人觉得这很有用;再见。

【讨论】:

    猜你喜欢
    • 2019-01-10
    • 2011-11-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多