views:

733

answers:

6

Hi,

I have a windows forms app in C#. Platform is vS 2005.

Following is the piece of code:

namespace HostApp
{
    public partial class Form1 : Form
    {
        private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
        {            
            comboBox2.Items.Add("Apples");
            comboBox2.Items.Add("Oranges");
            comboBox2.Items.Add("Grapefruits");
        }
    }
}

I run the app but the fruit names do not show up in the drop down of comboBox2. I am sure I am missing some line of code to "populate" the drop down with the entered values. Any help would be much appreciated.

Thanks, Viren

+3  A: 

You add the items in the handler for the SelectedIndexChanged event. You need to move the code to InitializeComponent or another appropriate place.

Martin Liversage
thanks..that worked..thank you for your quick reply on my silly question..i am new to c#..thanks anyways..
VP
A: 

Move the code to the Page_Load event ...

The SelectedIndexChanged only fires when the ComboBox index has changed AND AutoPostBack = True.

EDIT: Sorry, it's a Form, I was thinking web ... move to Form_Load

Martin
+1  A: 

Please check the following things:

  1. You have added AutoPostBack="true" in the combo-box so that the selectedChange event is fired and post back happens.
  2. Make sure you have nothung in ur Page load which refreshed the combo box. You can use IsPostBack to acheive loading of the values.
Bhaskar
This question is about Windows Forms, not ASP.NET.
Martin Liversage
+1  A: 

Your items are being added when the selected item is changed, but as there are no existing items this will never happen. Move those lines to the constructor for Form1 and it'll work.

Steve Beedie
A: 

The code you provided will only add items to comboBox2 when the selection changes in the control that is hooked up to comboBox2_SelectedIndexChanged.

There are two concepts at play here: Control Initialization/Databinding, and event handling.

The code you have written essentially says "If somebody selects something new in the combo box, add these 3 options to the combo box". That would happen every time the selected index changes in the combo box. This, of course, assumes you have even hooked up this event handler to the combo box to begin with. This is event handling.

What you are probably trying to do is initialize the control. This happens when you load the page and want to setup the initial options available in your page controls. Using the Init or Load event is probably where you want to setup the choices in your control. This is also when you would initialize your event handlers to say "When something happens, do this".

Jay S
A: 
djerry