我想问一些关于组合框和文本框的帮助。所以这就是问题,我一直试图弄清楚如何使用组合框将值分配到文本框中,这就是它的样子
If yearlevel.SelectedItem = "Nursery" Then
txtamount.Text = "1000"
If yearlevel.SelectedItem = "Kinder" Then
txtamount.Text = "2000"
End If
End If
我想要发生的是,当我选择“幼儿园”时,“1000”会自动出现在文本框中。
答案 0 :(得分:1)
If yearlevel.SelectedItem = "Nursery" Then
txtamount.Text = "1000"
ElseIf yearlevel.SelectedItem = "Kinder" Then
txtamount.Text = "2000"
End If
如果这不符合您的要求,请解释您的问题 简而言之。
答案 1 :(得分:1)
使用SelectedIndexChanged事件:
Private Sub yearLevel_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles yearLevel.SelectedIndexChanged
Select Case yearLevel.SelectedItem.ToString
Case "Nursery" : txtAmount.Text = "1000"
Case "Kinder" : txtAmount.Text = "2000"
End Select
End Sub
为了使其更加动态和简单,当您将项目添加到组合框中时,将其添加为包含文本和金额的对象,然后当selectedindexchanged发生时,只需将selectedobject转换回您自己的对象并使用金额值:
Private Structure YearLevelItemStruct
Private _Text As String
Private _Amount As Double
Public ReadOnly Property Text() As String
Get
Return Me._Text
End Get
End Property
Public ReadOnly Property Amount() As Double
Get
Return Me._Amount
End Get
End Property
Public Sub New(ByVal Text As String, ByVal Amount As Double)
Me._Text = Text
Me._Amount = Amount
End Sub
Public Overrides Function ToString() As String
Return _Text
End Function
End Structure
Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
loaditems()
End Sub
Sub loaditems()
yearLevel.Items.Clear()
yearLevel.Items.Add(New YearLevelItemStruct("Nursery", 1000))
yearLevel.Items.Add(New YearLevelItemStruct("Kinder", 2000))
End Sub
Private Sub yearLevel_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles yearLevel.SelectedIndexChanged
txtAmount.Text = DirectCast(yearLevel.SelectedItem, YearLevelItemStruct).Amount.ToString
End Sub
当然,如果你已经拥有某些列表中的所有项目或某些具有ToString()的对象的数组,那么你就不需要创建一个自己的结构来保存该对象。 如果您的对象没有ToString(),那么您可以使用组合框:s .DisplayMember =“some_property_that_returns_a_string”。因为如果它没有暴露ToString(并且你不使用.DisplayMamber),那么组合框将填充类型的名称而不是文本。