2011-11-23 44 views
1

我想問一些關於組合框和文本框的幫助。所以這裏的,我一直在試圖找出如何使用組合框的值分配到文本框,這裏的問題是它看起來像如何使用組合框在文本框中插入值

If yearlevel.SelectedItem = "Nursery" Then 
    txtamount.Text = "1000" 
    If yearlevel.SelectedItem = "Kinder" Then 
     txtamount.Text = "2000" 
    End If 
End If 

我想發生什麼事是,當我選擇「託兒所」 「1000」會自動出現在文本框中。

+0

你如何綁定到組合框?什麼是數據類型? – Oded

回答

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),那麼組合框將被填充類型的名稱而不是文本。

+0

waaaahhh ~~謝謝〜!你是一個拯救生命的人! – trisha0906

+0

我會試試這個,再次感謝你〜! – trisha0906

1
If yearlevel.SelectedItem = "Nursery" Then 
    txtamount.Text = "1000" 
ElseIf yearlevel.SelectedItem = "Kinder" Then 
    txtamount.Text = "2000" 
End If 

如果這不符合您的要求,請詳細解釋您的問題 。

+0

我已經試過了,它沒有工作。我也嘗試使用.SelectedText並沒有發生任何事情。我在我的組合框中有幾個項目,我想要做的是當用戶在組合框中選擇時,它的等效量將自動出現在文本框 – trisha0906

相關問題