我有一个组合框,其值为“Internet,Games,print(short),print(long)”...我想要的是如果我在组合框中选择Internet,则文本框“t_amount”应该填充为“20”
这是我的代码......
Private Sub C_job_SelectedIndexChanged(sender As Object, e As EventArgs) Handles C_job.SelectedIndexChanged
If C_job.SelectedIndex = "Internet" Then
t_amount.Text = "20"
ElseIf C_job.SelectedIndex = "Games" Then
t_amount.Text = "10"
ElseIf C_job.SelectedIndex = "Print (short)" Then
t_amount.Text = "1"
ElseIf C_job.SelectedIndex = "Print (long)" Then
t_amount.Text = "2"
End If
End Sub
答案 0 :(得分:0)
我不是专家,但认为您应该使用“选定值”更改,或者如果使用索引则这是一个数字索引,即“互联网”将是索引编号0.
HTH
答案 1 :(得分:0)
SelectedIndex
属性返回索引,这是一个数字。不是字符串。组合框中的第一项将具有0的索引,下一项的索引为1,等等。
或者,要获取字符串,请使用SelectedItem.ToString()
:
Private Sub C_job_SelectedIndexChanged(sender As Object, e As EventArgs) Handles C_job.SelectedIndexChanged
Dim selected As String = C_job.SelectedItem.ToString()
If selected = "Internet" Then
t_amount.Text = "20"
ElseIf selected = "Games" Then
t_amount.Text = "10"
ElseIf selected = "Print (short)" Then
t_amount.Text = "1"
ElseI fselected = "Print (long)" Then
t_amount.Text = "2"
End If
End Sub
答案 2 :(得分:0)
你已经有了答案,但我认为代码可以稍微改进一下。根据经验,如果我要对列表中的多个项目对单个变量进行检查,则使用Select Case
而不是正在进行的ElseIf
语句列表。最重要的原因是,如果你在第一个上改变某些东西,你必须记住在所有其他东西上改变它。 CodeGray通过将值声明为局部变量解决了一些问题,但可读性仍然有待提高,所以请尝试这样做:
Select Case C_job.SelectedItem.ToString
Case "Internet"
t_amount.Text = "20"
Case "Games"
t_amount.Text = "10"
Case "Print (short)"
t_amount.Text = "1"
Case "Print (long)"
t_amount.Text = "2"
End Select
另外,我只想检查您是否正确使用了ComboBox的Display Member
和Value Member
。您可以在组合框中公开具有本机支持的两个属性,一个是显示给用户的值,另一个是后备属性。当您执行代码时,您将可以访问这两个代码。好的一面是,您可以以更具说明性的方式存储此信息,然后做出相应的反应。
当ComboBox有选择时,该信息存储在SelectedItem
属性中,该属性存储用于填充该下拉项的原始对象。如果您为组合框项目定义了DisplayMember
和ValueMember
,则SelectedText
和SelectedValue
将仅显示所选对象的这些属性。
这是设置
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim dataSource As New DataTable
With dataSource.Columns
.Add("Display", GetType(String))
.Add("Value", GetType(Integer))
End With
With dataSource.Rows
.Add("Internet", 20)
.Add("Games", 10)
.Add("Print (short)", 1)
.Add("Print (long)", 2)
End With
With C_job
.DisplayMember = "Display"
.ValueMember = "Value"
.DataSource = dataSource
End With
End Sub
正面,现在是处理事件所需的所有代码
Private Sub C_job_SelectedIndexChanged(sender As Object, e As EventArgs) Handles C_job.SelectedIndexChanged
t_amount.Text = C_job.SelectedValue
End Sub
如果您愿意,这也会使您很容易绑定此属性,因为您已经预先编写了所有逻辑。