Vb.net Visual Basic,将组合框值存储在变量中
我想将comboBox值保存在一个变量中。但每当我更改comboBox值时,设置的值都是null,所选索引显示为“-1”。下面是我的代码Vb.net Visual Basic,将组合框值存储在变量中,vb.net,combobox,Vb.net,Combobox,我想将comboBox值保存在一个变量中。但每当我更改comboBox值时,设置的值都是null,所选索引显示为“-1”。下面是我的代码 Private Sub SelectedIndexChanged(sender As Object, e As EventArgs) Handles ComboBox1.SelectedIndexChanged Dim form As CreateEvalForm = New CreateEvalForm //windows Form Dim
Private Sub SelectedIndexChanged(sender As Object, e As EventArgs) Handles ComboBox1.SelectedIndexChanged
Dim form As CreateEvalForm = New CreateEvalForm //windows Form
Dim str As String = form.ComboBox1.SelectedIndex
MessageBox.Show(str) //shows null
Dim openingId As Integer = Val(form.ComboBox1.Text)
End Sub
谁能提出一个解决方案
Private Sub SelectedIndexChanged(sender As Object, e As EventArgs) Handles ComboBox1.SelectedIndexChanged
Dim str As String = ComboBox1.SelectedIndex
MessageBox.Show(str)
Dim openingId As Integer = Val(ComboBox1.Text)
End Sub
这行吗?但是,如果希望从组合框的选定值中选择一个值,则应尝试以下操作:
dim openingId as Integer = Val(comboBox1.SelectedValue)
在这一行中,您正在创建一个新表单,因此该新表单上的组合框也将是新的,并且没有选定的索引
您可以这样使用组合框:
Dim str As String = ComboBox1.SelectedIndex
或
SelectedIndex是一个整数,而不是字符串。ComboBox1.SelectedItem比ComboBox1.Text稍微好一点。@muffi,
SelectedItem
并不比Text
好。它们都符合预期目的Text
专门获取控件中所选项目的文本,而SelectedItem
获取项目本身。你应该使用哪一种取决于你想要哪一种。如果在下拉列表中添加了Strings
,则两者将返回相同的内容,尽管Text
是typeString
,而SelectedItem
是typeObject
。如果您设置了DisplayMember
,那么它们就不是同一件事了。当然,您没有选择任何项目。您正在处理当前窗体上控件的事件,然后在事件处理程序中创建一个全新窗体并访问该窗体上的控件。该表单甚至还没有显示,因此当然没有在其上选择任何内容。去掉创建新表单的代码,然后访问当前表单上的组合框
。@jmcilhinney yep,有效:)
Dim str As String = ComboBox1.SelectedIndex
Dim str As String = Me.ComboBox1.SelectedIndex