2011-12-11 104 views
0

我有一個vb.net應用程序,並且我有一個應該包含顯示成員(文本)和值成員(整數)的組合框。combobox默認值

問題是: 我想爲窗體加載時設置一個默認值爲該組合框,但我沒有加載事件,因爲我動態地創建窗體和組合框。我使用了combobox.selectedvalue = 6,但它不起作用。

注意:我無法使用selectedindex屬性,因爲有時值來自DB表主鍵,它與組合框索引不同。

代碼:

Private Sub fill_combo(ByRef combo As ComboBox, ByVal nodes As HashMap) 
    Dim comboData = New BindingList(Of KeyValuePair(Of Integer, String)) 

    nodes.movefirst() 
    Do While Not nodes.eof 
     If check_atrbValue(nodes.key, nodes.value, "string", "other") Then 
     comboData.Add(New KeyValuePair(Of Integer, String)(nodes.key, nodes.value)) 
     End If 
     nodes.movenext() 
    Loop 
    combo.DataSource = comboData 
    combo.ValueMember = "Key" 
    combo.DisplayMember = "Value" 
    combo.selectedvalue=6 
End Sub 
+0

你似乎已經在你的代碼:'combo.selectedvalue = 2',儘管實際情況應該是:'combo.SelectedValue = 2'。 – Oded

+0

我不理解你的評論。 –

+0

來自oded的評論大約是小寫/大寫:S當選V alue vs s當選v alue。 – GameAlchemist

回答

0

你有一個加載的情況下,即使你創建的UIElement動態。但是,因爲你創造了它這樣,你也應該在代碼掛鉤事件處理程序的背後:

AddHandler mycombobox.Loaded, Sub(sender As System.Object, 
         e As System.Windows.RoutedEventArgs) _ 
            CType(sender, ComboBox).SelectedIndex = 2 

但也許你會想太多掛鉤到另一個事件,就像一個指出數據從您的數據庫加載中...

AddHandler ??.DataAvailable, Sub(???) SelectionComboBox.SelectedIndex = 2 

其中SelectionComboBox是你初始化/你的類的成員與代碼添加後面。和DataAvailable是你的事件。它可能是這樣的:

Public Event DataAvailable(ByVal DefaultValue As Integer) 

所以你可以在事件處理程序中使用該值。 (只是一個想法):=)。

不要忘記,如果你添加/刪除幾次組合框,以移除處理程序(以避免內存泄漏)