2010-10-21 50 views
1

我正在創建一個動態組合框並添加到表單中。我試圖用ArrayList中的DataSource填充組合框,然後在組合框中根據屬性的值選擇一個項目。動態組合框數據源表單加載

問題是組合框項目直到Form_Load事件完成並且窗體可見之後纔會被綁定。所以當我嘗試設置組合框的選定索引時,組合框是空的。見我在做什麼詳細的代碼,並參考意見代碼:

Dim cboValues As New ComboBox 
cboValues.Width = fieldControlWidth 
cboValues.DropDownStyle = ComboBoxStyle.DropDownList 

cboValues.Name = "cboResult" 

For Each d As SystemTaskResult In [Enum].GetValues(GetType(SystemTaskResult)) 
    Dim cv As New ComboBoxDisplayValue(d.ToString, d) 
    arrValues.Add(cv) 
Next 

cboValues.DataSource = arrValues 
cboValues.DisplayMember = "Display" 
cboValues.ValueMember = "Value" 

Dim val As SystemTaskResult = DirectCast(p.GetValue(Me.Task, Nothing), SystemTaskResult) 

'Was trying to get this to work, but commented out to try the below 
'cboValues.SelectedIndex = cboValues.Items.IndexOf(New ComboBoxDisplayValue(val.ToString, val)) 

'Then this doesn't work because the combo box hasn't updated it's DataSource yet, which is probably the reason for the above not working as well. 
For i = 0 To cboValues.Items.Count - 1 
    cboValues.SelectedIndex = i 
    If cboValues.SelectedValue = val Then 
     Exit For 
    End If 
Next 

holdPanel.Controls.Add(cboValues) 

如何選擇選擇組合框指數沒有一個黑客(加載定時器或一些愚蠢的類似)的權利?

回答

0
+0

謝謝您的回答,但組合框中的項目仍在0在Form.Shown事件。請記住,這是一個動態控件,而不是表單上的控件。我認爲這是這個問題。 – ScottN 2010-10-21 18:46:42

+0

@ScottN不知道爲什麼你堅持要在同一個函數中執行它們,但是你也可以嘗試在Shown事件上創建組合框 – 2010-10-21 18:50:26

+0

對不起,如果我在Form Load中做了我的控件創建,然後在Form Shown中嘗試將組合框設置爲正確的選定索引項目現在填充,我希望能夠在相同的功能做到這一點。我想不可能。 – ScottN 2010-10-21 18:51:13