Thursday, April 28, 2011

How do I set a comboBox.selecteditem

I have:

ComboBox.DataSource = System.Enum.GetValues(typeof(ImageLayout));

but how do I set the ComboBox.SelectedItem to an ImageLayout value?

I tried..

LayOutCB.SelectedItem = (int)ImageLayout.Center;

but I get an exception


Update:

originally I was trying to set the SelectedItem in the constructor of the UserControl.

I added the event Handler

this.Load += new EventHandler(PageSettings_Load);

and then set the combobox.SelectedItem in there.

void PageSettings_Load(object sender, EventArgs e)
{                 
  LayOutCB.SelectedItem = ImageLayout.Center;
}

Works real good now.

so what was that about? can someone explain please.

From stackoverflow
  • Try something like this:

    ComboBox.SelectedItem = (int)ImageLayout.Foo;
    

    replacing int with the underlying type of your enumeration. Honestly it may just work without the cast but I am not anywhere near csc.exe right now.

  • Have you not tried this?

    ComboBox.SelectedItem = ImageLayout.Center
    

    It works perfectly fine for me.


    Edit:

    With regards to your update, I believe you are setting the SelectedItem before calling InitializeComponent() and the combo box was not created yet give you the object reference exception (the box was defined but not assigned.)

    Brad : it throws an exception of "Object Reference not set to an instance of an Object"
    Samuel : Then you have to post more code, because on a simple form with a combobox, it works.
  • The ComboBox control in Windows.Forms is a wrapper around the underlying Windows Control. This is a common pattern - most of the Windows.Forms controls are this kind of wrapper.

    Some of the properties of the ControlBox - like SelectedItem - cannot be set until after the underlying Windows handle is created. Typically, handle creation occurs when the control is first displayed.

    When in your User Control's constructor, this code:

    LayOutCB.SelectedItem = (int)ImageLayout.Center;
    

    would have thrown an exception because the handle was unavailable. It worked later on (in your event handler) because the handle was available.

    Brad : Bevan - thanks for the info.

0 comments:

Post a Comment