2
Answers

checking for selection in listbox

flipnjme

flipnjme

20y
2.3k
1
I'm trying to check if a value from a list box is selected, right now if a value isn't selected and some one clicks add "I get specified argument was out of range of values". I figure maybe an if statement would work to check if anything was selected before the code is executed. Here is the code I have. public void Add_Click(object sender, System.EventArgs e) { ListViewItem item = listView1.SelectedItems[0]; Form1.FileSel = textBox1.Text; Form1.FileSize = item.SubItems[1].Text; Form1.selected = 1; this.Close(); } any help would be greatly appreciated.
Answers (2)
0
flipnjme
NA 15 0 20y
Thanks for the help it worked
0
Mykonine
NA 520 0 20y
Take a look at this line. ListViewItem item = listView1.SelectedItems[0]; ListView.SelectedItems is a property that returns a ListViewItemCollection. If no items are selected, the collection is empty. Like any empty array with zero values in it, an exception will be thrown when you try to get the first value when it doesn't exist. To fix this problem, you'll need to insert an if statement. ... ListViewItem item; if (listView1.SelectedItems.Count > 0) item = listView1.SelectedItems[0]; ...