ComboxBox Binding fires SelectedIndexChanged

When binding my combobox to a dataset, i notice that my SelectedIndexChanged event is firing for each row of data that is bound.

I only want to handle this event when user changes the selection in the combobox.

What am i Missing

Thanks



Answer this question

ComboxBox Binding fires SelectedIndexChanged

  • PromisedOyster2

    That's odd. Are you sure it was firing the event



    protected void Form_Load( object sender, EventArgs e )
    {
         DataSet dtsData = GetData(); //obtain data.

         this.cboCombo.DataSource = dtsData.tblDataTable;
         this.cboCombo.DisplayMember = "displayName";
         this.cboCombo.ValueMember = "displayId";
    }

    protected void cboCombo_SelectedIndexChanged( object sender, EventArgs e )
    {
         MessageBox.Show( this, "Display text is = " + this.cboCombo.SelectedText );
    }

     

    Did you code something like this


  • atmuc

    Thanks for the information.  I used the Loading Flag and it worked perfectly.


  • jrmartinez

    The ComboBox fires SelectedIndexChanged when it binds (indicating that it's going from -1 to 0).  When DisplayMember is set, it re-binds (it has to show a different set of items).

    If you're loading data repeated, I'd use the loading flag, as you have.  If you're loading data only once, another option is to hook up the event after the DataSource/DisplayMember are set.

    protected void Form_Load( object sender, EventArgs e )
    {
        DataSet dtsData = GetData();
    //obtain data.

         this.cboCombo.DataSource = dtsData.tblDataTable;
         this.cboCombo.DisplayMember = "displayName";
         this.cboCombo.ValueMember = "displayId";

         this.cboCombo.SelectedIndexChanged += new EventHandler(cbo_SelectedIndexChanged);
    }


    -Scott

  • DGVA

    That's how it works.  I usually have to set a class-scope boolean member to keep track of when the combobox is being bound, so that I can short-circuit the selectedindexchanged event.

    private bool _loading;

    protected void Form_Load( object sender, EventArgs e )
    {
        this._loading = true;
        DataSet dtsData = GetData();
    //obtain data.

         this.cboCombo.DataSource = dtsData.tblDataTable;
         this.cboCombo.DisplayMember = "displayName";
         this.cboCombo.ValueMember = "displayId";

        this._loading = false;
    }

    protected void cboCombo_SelectedIndexChanged( object sender, EventArgs e )
    {
        if(this._loading) return;

        MessageBox.Show( this, "Display text is = "+this.cboCombo.SelectedText );
    }




  • ComboxBox Binding fires SelectedIndexChanged