winformslistboxselecteditemlistboxitemselectedindexchanged

How to update item in ListBox in WindowsForm Application in C#


I have created a windows form application in which there is a ListBox to display items. When I click on an item it gets selected as I have implemented lst_items_SelectedIndexChanged() method, and values are loaded in the controls to be update. But when I change the value from the controls to update the selected index in also called and throws Index Out of Bounds -1 Exception.

Here is my SelectedIndexChanged Code:

private void lst_items_SelectedIndexChanged(object sender, EventArgs e)
{
    ShoppingItem myItem = new ShoppingItem();
    if (lst_items.SelectedIndex > -1)
    {
        myItem = itemManager_obj.GetItem(lst_items.SelectedIndex);
        txt_amount.Text = myItem.amount.ToString();
        txt_description.Text = myItem.description;
        cmb_units.SelectedIndex = (int)myItem.unit;
    }
}

Here is my Update(change) button code:

    private void btn_change_Click(object sender, EventArgs e)
    {
        ShoppingItem itemToChange = new ShoppingItem();
        itemToChange = itemManager_obj.GetItem(lst_items.SelectedIndex);

        bool success = false;

        itemToChange = ReadIput(out success);
        if (success)
        {
            success = itemManager_obj.ChangeItem(itemToChange,lst_items.SelectedIndex);
            lst_items.Items.RemoveAt(lst_items.SelectedIndex);
            lst_items.Items.Insert(lst_items.SelectedIndex, itemManager_obj.ToString());
            UpdateGUI();
        }
    }

I am not sure why SelectedIndexChanged is called on update after this line of code is executed:

lst_items.Items.RemoveAt(lst_items.SelectedIndex);

Any idea how can I update without getting an exception index out of bound? Regards


Solution

  • Store this in an int

    lst_items.Items.RemoveAt(lst_items.SelectedIndex);

    then do

    lst_items.Items.Insert(your int, itemManager_obj.ToString());

    You are getting this error because after you remove the selectedIndex, there is no longer an item selected because that item doesn't exist.

     if (success)
     {
        int indexer=lst_items.SelectedIndex;
        success = itemManager_obj.ChangeItem(itemToChange,lst_items.SelectedIndex);
        lst_items.Items.RemoveAt(indexer);
        lst_items.Items.Insert(indexer, itemManager_obj.ToString());
        UpdateGUI();
     }