問題描述
vb.net ‑ 組合框總是選擇第一個值 (vb.net ‑ combo box always select the first value)
美好的一天,誰能幫我解決這個問題。我有兩個用於月份(01‑12)的組合框,用於monthstart和monthend。現在,每次我選擇十月(10)時,它顯示的值都是 01。對不起。我是 vb 的新手。
有沒有其他方法可以做到這一點?有什麼建議嗎?
謝謝。
Private Sub ValueComboxformonth()
Dim comboSource As New Dictionary(Of String, String)()
comboSource.Add("01", "January")
comboSource.Add("02", "February")
comboSource.Add("03", "March")
comboSource.Add("04", "April")
comboSource.Add("05", "May")
comboSource.Add("06", "June")
comboSource.Add("07", "July")
comboSource.Add("08", "August")
comboSource.Add("09", "September")
comboSource.Add("10", "October")
comboSource.Add("11", "November")
comboSource.Add("12", "December")
cmbAppliedMonthStart.DataSource = New BindingSource(comboSource, Nothing)
cmbAppliedMonthStart.DisplayMember = "Value"
cmbAppliedMonthStart.ValueMember = "Key"
cmbAppliedMonthEnd.DataSource = New BindingSource(comboSource, Nothing)
cmbAppliedMonthEnd.DisplayMember = "Value"
cmbAppliedMonthEnd.ValueMember = "Key"
End Sub
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
ValueComboxformonth()
Dim monthkeystart As String = DirectCast(cmbAppliedMonthStart.SelectedItem, KeyValuePair(Of String, String)).Key
Dim monthvaluestart As String = DirectCast(cmbAppliedMonthStart.SelectedItem, KeyValuePair(Of String, String)).Value
Dim monthkeyend As String = DirectCast(cmbAppliedMonthEnd.SelectedItem, KeyValuePair(Of String, String)).Key
Dim monthvalueend As String = DirectCast(cmbAppliedMonthEnd.SelectedItem, KeyValuePair(Of String, String)).Value
End Sub
monthkeystart的值是01 monthvaluestart的值是一月
參考解法
方法 1:
This is due to you calling the ValueComboxformonth
method before reading the values. That method resets the datasource for the combo‑boxes, and it defaults to the first value.
Try moving that call to the constructor (New
method) of the form.
Public Sub New()
...
ValueComboxformonth()
End Sub