Search code examples
c#winformslistviewiconvertible

Cast listviewitem to System.IConvertible


I have following issue... I got a listview in which I have some numbers (ID's). Now I want to arrange them with some listboxes so that I can do a typical SQL search (with OR, AND). So the listview gets filled that way:

 for (int i = 0; i < simIdCells.Count; i++)
            {
                ListViewItem store = new ListViewItem(simIdCells[i]);
                store.SubItems.Add(simNameCells[i]);
                form5.listViewCap.Items.Add(store);
                form5.listViewCap.Items[0].Selected = true;
                form5.listViewCap.Select();
            }

So there is always a value selected in my listview. When I now want to do the search I use this code to first fill my elements into a list:

   foreach(var selectedItem in listView1.SelectedItems)
        {
           simIdElements.Add(Convert.ToInt32(selectedItem));
        }

Now I get the following exception:

object of type "System.Windows.Forms.ListViewItem" can not be converted to the type "System.IConvertible".

How do I solve this problem?


Solution

  • ListViewItem cannot be converted to integer. You should either convert back item text to int or use it's Tag property to keep the integer value with the item.

    First approach:

    foreach(ListViewItem selectedItem in listView1.SelectedItems)
    {
         string text = selectedItem.Text;
         simIdElements.Add(Convert.ToInt32(text));
    }
    

    Second approach:

    for (int i = 0; i < simIdCells.Count; i++)
    {
        int value = simIdCells[i];
        ListViewItem store = new ListViewItem(value.ToString());
        store.Tag = value;
        ListViewItem subItem = new istViewItem(value.ToString());
        subItem.Tag = value;
        store.SubItems.Add(subItem);
        form5.listViewCap.Items.Add(store);
        form5.listViewCap.Items[0].Selected = true;
        form5.listViewCap.Select();
    }
    ...
    ...
    foreach(var selectedItem in listView1.SelectedItems)
    {
        simIdElements.Add((int)selectedItem.Tag);
    }