0

我有一个组合框,其值为“互联网,游戏,打印(短),打印(长)”......我想要的是如果我在组合框中选择互联网,文本框“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
4

3 回答 3

0

我不是专家,但认为您应该使用“选定值”更改,或者如果使用索引那么这是一个数字索引,即“互联网”将是索引号 0。

高温高压

于 2013-08-11T13:46:59.717 回答
0

SelectedIndex属性返回一个index,它是一个数字。不是字符串。组合框中的第一项的索引为 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
于 2013-08-11T13:50:27.893 回答
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 MemberValue Member。您可以在组合框中公开两个具有本机支持的属性,一个是要显示给用户的值,另一个是支持属性。当您执行代码时,您将可以访问两者。好处是您可以以更具声明性的方式存储这些信息,然后做出相应的反应。

当 ComboBox 有一个选择时,该信息将存储在SelectedItem存储用于填充该下拉项的原始对象的属性中。如果您为组合框项目定义了DisplayMemberand ValueMember,则SelectedTextandSelectedValue将只公开所选对象的那些属性。

这是设置

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

如果您愿意,这也将使绑定此属性变得非常容易,因为您已经预先编写了所有逻辑。

于 2013-08-11T16:13:03.070 回答