views:

12

answers:

1

Hi all,

I'm creating a dynamic combo box and adding to a form. I'm trying to fill the combo box with a DataSource from an ArrayList and then selecting an item in the combo box based off a value from a property.

Problem is, the combo box items don't get bound until after the Form_Load event has finished and the form is visible. So the combo box is empty when I try to set the selected index of the combo box. See code for what I'm doing in detail, and refer to comments in code:

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)

How to select the right selected index for combo box without a hack (Load timer or something stupid like that)?

A: 

Try Form.Shown. See :

http://stackoverflow.com/questions/218732/how-do-i-execute-code-after-a-form-has-loaded

ohadsc
@ohadsc, thanks for your answer, but the combo box items are still 0 in the Form.Shown event. Remember this is a dynamic control, not a control already on the form. Which I think is the issue here.
ScottN
@ScottN Not sure why you insist on doing them in the same function, but you can try creating the ComboBox on the Shown event as well
ohadsc
@ohadsc, Sorry, if I do my control creation in the Form Load, and then in the Form Shown try to set the combo box to the correct selected index the items are now populated, I was hoping to do this in the same function. I guess not possible.
ScottN