【问题标题】:Can not change the value of a combobox in an user control from another form无法从其他表单更改用户控件中组合框的值
【发布时间】:2020-03-18 17:23:05
【问题描述】:

我在 Autocad 中有一个用户控件,可以根据特定标准制作图纸。 从这个用户控件,可以打开另一个用于填写特定数据的表单。 当我尝试使用表单中的数据自动更改用户控件中的组合框时,它会给出错误:

对非共享成员的引用需要对象引用。

现在我在互联网上查找了这个,但我似乎无法应用给出的解决方案。 我的情况如下:

Partial Public Class Partial Public Class User_Control
    Private Form1 As New Form_Something
  private sub button1_click(sender As Object, e As EventArgs) Handles button1.Click
    Form1.show()
  End sub
End Class

此用户控件有一个 Combobox,我们将其命名为 Combobox1。现在,当我更改 Form_Something 上的值时,Combobox1 也必须更改。 所以我在Form1中有以下代码:

Partial public class Form_Something
    Public Sub Button1_Click(sender As Object, e As EventArgs) Handles BT_Apply.Click
       User_Control.Combobox1.text = "Apples"
    End sub
End class

这给出了上述错误。 有人可以帮我解决这个问题吗,因为我想用多个组合框/标签等来做这个。

【问题讨论】:

  • 请注意您必须引用特定的ComboBox 来影响该控件,而不仅仅是ComboBox 类?有道理,因为您可以有多个ComboBoxes。那么,为什么您认为您可以只引用您的 User_Control 类并影响该类型的特定实例?如果你能做到这一点并且你有多个实例,你期望会发生什么?您需要参考您想要影响的实际实例,而不仅仅是它的类型。
  • 可能需要确保您在 FormSomething 中的 ComboBox1 上也正确设置了修饰符属性
  • 谢谢@jmcilhinney,所以当我从表单中引用用户控件时,我必须引用用户控件的特定实例或组合框的特定实例?
  • @Hursey 谢谢,我已经将修饰符设置为public,但它没有帮助

标签: vb.net autocad


【解决方案1】:

为了更直观的展示给大家,我这里改了UserControl1BorderStyle。您可以根据需要对其进行更改或评论。

我已经对代码的一些关键部分进行了评论,如果您仍然感到困惑,请告诉我。

如果我的帖子有助于解决您的问题,请点击该帖子的“标记为答案”。通过将帖子标记为已回答或有帮助,您可以帮助其他人更快地找到答案。

结果如下:

我的代码如下:

1.Form1代码:

Public Class Form1
    Private Sub Button1_Click(sender As Object, e As EventArgs)
        MyUserControl.ComboBox1.Text = "Apples"
    End Sub
End Class

2.UserControl1代码:

Public Class UserControl1

    Private Sub UserControl1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        ComboBox1.Text = "Apple"
        Me.BorderStyle = BorderStyle.Fixed3D
    End Sub

    Dim myForm As Form
    Dim btn As Button
    Dim txtbox As TextBox

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click

        myForm = New Form With {.Text = "myForm"}
        btn = New Button With {.Text = "Save", .Height = 30, .Width = 60, .Top = 100, .Left = 150}
        txtbox = New TextBox With {.Text = "", .Height = 20, .Width = 100, .Top = 100, .Left = 20}

        myForm.Controls.Add(btn)
        myForm.Controls.Add(txtbox)

        myForm.Show() 'Open dialog in modeless window

        AddHandler btn.Click, AddressOf Btn_Click
    End Sub

    Sub Btn_Click(sender As System.Object, e As System.EventArgs)
        Me.ComboBox1.Text = txtbox.Text 'This step is important!
        myForm.Close()
    End Sub

End Class

【讨论】:

  • 谢谢!有效。我必须重建我的表格,但我会管理的。非常感谢,这一直困扰着我一段时间,在未来的项目中,我可以从一开始就以正确的方式构建代码。
猜你喜欢
  • 1970-01-01
  • 2017-05-20
  • 2017-11-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-11-18
相关资源
最近更新 更多