Search code examples
c#.netlistlistviewstreamreader

InvalidArgument=Value of '0' is not valid for 'index' when trying to get only selected item in a ListView


So I am trying to remove an item from a listview and a line from a text. I've used the SelectedItems[0] and it gives me an error. And yes I do have multiselect set to false.

error log:

 InvalidArgument=Value of '0' is not valid for 'index'.

my code:

        DialogResult msgBox = MessageBox.Show("Are you sure you want to remove this port?", "Are you sure?", MessageBoxButtons.YesNo, MessageBoxIcon.Question);

        if (msgBox == DialogResult.No)
        {
            // Do nothing
        }
        if (msgBox == DialogResult.Yes) 
        {
            listView1.SelectedItems[0].Remove();

            StreamReader sr = File.OpenText("ports.cfg");
            string srStr = sr.ReadToEnd().ToString();
            sr.Close();

            List<String> linesList = File.ReadAllLines("ports.cfg").ToList();
            linesList.RemoveAt(listView1.SelectedItems[0].Index);
            File.WriteAllLines("ports.cfg", linesList);
            linesList.ToArray();
        }

Solution

  • Impossible to tell without a proper minimal, reproducible example. But in the code above, you appear to first remove the desired item from the ListView itself, and then you attempt to retrieve the Index property from the same item, presumably the one you just removed.

    SelectedItems will wind up empty as a result of removing the item (since you say you "…have multiselect set to false"), so when you try to retrieve the element at index 0, of course there's not one there.

    Even if there was, you would not wind up getting the item you actually wanted, because you've already removed from the SelectedItems collection the one you want to remove from linesList later. Any item still left in the SelectedItems collection would be a completely different item, and not the one you wanted to remove from the ports.cfg file.

    Something like this would, I think, work better:

    ListViewItem portItem = listView1.SelectedItems[0];
    int portIndex = portItem.Index;
    
    portItem.Remove();
    
    StreamReader sr = File.OpenText("ports.cfg");
    string srStr = sr.ReadToEnd().ToString();
    sr.Close();
    
    List<String> linesList = File.ReadAllLines("ports.cfg").ToList();
    linesList.RemoveAt(portIndex);
    File.WriteAllLines("ports.cfg", linesList);
    linesList.ToArray();
    

    The above, of course, assumes that by the time this code is reached, you've already confirmed that there is in fact an item selected. If that's not the case, then you also need to add a check for that, by inspecting the SelectedItems.Count property to make sure it's greater than 0.