开发者

Do I have to remove a selectedIndexChange event from a listBox when refreshing the data in it?

I have a listbox in which a have a series of cases retrieved from a database. When i create a new case i wan't to update the listBox to reflect the actual state of the cases-table in the database. But I get a NullReferenceException from the event handler for this line: populateBoxes((int)lb.SelectedValue) when i try to update it.

This is my event-handler on the listbox:

private void lbCases_SelectedIndexChanged(object sender, EventArgs e)
        {
            ListBox lb = (ListBox)sender;

            populateBoxes((int)lb.SelectedValue);
        }

The update event:

private void button1_Click(object sender, EventArg开发者_StackOverflows e)
        {

            this.casesTableAdapter.Fill(this.caseDB.cases);

        }

I've used the built-in feature of VSE2008 to set the datasource, displaymember and valuemember of the listbox.


You have to make sure that when the datasource is set the lbCases_SelectedIndexChanged either does not fire or ignores the event.

Either create a 'Loading' boolean to ignore the event or set the index to -1 and add a check in lbCases_SelectedIndexChanged for the -1 index value to prevent the exception.


Set the selectedindex to -1 and then populate the list box over.


I suggest, you do a check in that event handler:

    private void lbCases_SelectedIndexChanged(object sender, EventArgs e)
    {
        ListBox lb = sender as ListBox;
        if(lb == null)
            return;

        populateBoxes((int)lb.SelectedValue);
    }


Check the SelectedValue for null before you run the

if (lb.SelectedValue != null)
{
    populateBoxes((int)lb.SelectedValue);
}

Also, if you want to end up with a selected value, you will have to select it after you call:

this.casesTableAdapter.Fill(this.caseDB.cases);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜