c# ListViewItem gets stuck in edit mode when AfterLabelEdit event fires

260 Views Asked by At

As the title says, when the AfterLabelEdit fires, the ListViewItem gets stuck in edit mode even if I press return or click on empty space.

The error:

A first chance exception of type 'System.Collections.Generic.KeyNotFoundException' occurred in mscorlib.dll

This is what the code looks like:

    ListViewItem oldItem;

    private void listView_BeforeLabelEdit(object sender, LabelEditEventArgs e)
    {
        oldItem = listView.Items[e.Item]; // store the unedited item
    }

    private void listView_AfterLabelEdit(object sender, LabelEditEventArgs e)
    {
        // make sure the new label has been edited and isn't null
        if(e.Label != "" && e.Label != oldItem.Text)
        {
            // iterate through Dictionary<string, List<string>> dict, find values of the key named oldItem.Text
            foreach(var keyValuePair in dict)
            {
                if(keyValuePair.Key == oldItem.Text)
                {
                    foreach(string s in keyValuePair.Value)
                    {
                        if(s != "")
                            dict[e.Label].Add(s); // ----------------- Error
                    }
                }
            }
            dict.Remove(oldItem.Text);
        }
    }

I'm pretty sure the keys and values aren't null. Any ideas? Please ask if anything is still unclear.

0

There are 0 best solutions below