user222427
user222427

Reputation:

listview to string exception thrown

What I have going on is i am using

string proj = listView2.SelectedItems[0].ToString();

to capture the item of my selected listview item, this works fine the first around, when i click on another listview item it throw the exception of

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

Any thoughts?

    private void listView2_SelectedIndexChanged(object sender, EventArgs e)
    {
       string proj = listView2.SelectedItems[0].ToString();
    }

working:

        string proj ="";
        ListView.SelectedListViewItemCollection lv2si =
        this.listView2.SelectedItems;

        foreach (ListViewItem item in lv2si)
        {
            proj = item.ToString();
        }

Upvotes: 1

Views: 1134

Answers (3)

Jeff Ogata
Jeff Ogata

Reputation: 57783

The SelectedIndexChanged event is raised whenever the Selected property of a ListViewItem changes. This means the event is raised twice: once when the first item is deselected, and a second time when the item you clicked on is selected. Since you are not checking whether SelectedItems has any items, you get the exception the first time the event is raised.

As @Jeffrey L Whitledge shows in his answer, you can use SelectedItems.Count to determine whether any items are selected.

Upvotes: 1

Jeffrey L Whitledge
Jeffrey L Whitledge

Reputation: 59463

You should test that the index value is valid before you access it.

private void listView2_SelectedIndexChanged(object sender, EventArgs e) 
{ 
    string proj;
    if (listView2.SelectedItems.Count > 0)
        proj = listView2.SelectedItems[0].ToString(); 
    else
        proj = string.Empty;
} 

Upvotes: 1

Madhur Ahuja
Madhur Ahuja

Reputation: 22681

What if no item is selected in listview ? The collection will contain zero items and it will throw this exception.

Instead, obtain ListViewItemCollection and use foreach to iterate over it. As described in MSDN example: ListView.SelectedListViewItemCollection breakfast = this.ListView1.SelectedItems;

    double price = 0.0;
    foreach ( ListViewItem item in breakfast )
    {
        price += Double.Parse(item.SubItems[1].Text);
    }

http://msdn.microsoft.com/en-us/library/system.windows.forms.listview.selecteditems.aspx

Upvotes: 1

Related Questions