G F

G F

  • NA
  • 44
  • 6.7k

Selecting a Row from List View throws an error

Jan 25 2020 12:49 AM
Hi,
 
I have a list view that pulls records from a Database, and that works.
 
I want to select a row and pass the record Name, Number and Date to three Text Boxes.
 
With the code I have, I can do that just fine, but just once.  I select the customer from a listbox, then it displays that customer's records in a seperate listview. 
 
If there are no records, there is no problem.
If there is one record, there is no problem.
If there is more than one record, I can click on any record in the list, and it passes the Name, Number and Date to my textboxes, which is what I want.
 
But, here is the problem, if I select a second record then it throws this error:
 
System.ArgumentOutOfRangeException: 'InvalidArgument=Value of '0' is not valid for 'index'.
Parameter name: index'
 
This is my code which retrieves the records from my database and populates listView1 (this works just fine):
  1. try  
  2. {  
  3. conDataBase3.Open();  
  4. myReader = cmdDataBase.ExecuteReader();  
  5. while (myReader.Read())  
  6. {  
  7. ListViewItem item = new ListViewItem(myReader["RUAName"].ToString());  
  8. item.SubItems.Add(myReader["RUANumber"].ToString());  
  9. item.SubItems.Add(myReader["RUAExpiryDate"].ToString());  
  10. listView1.Items.Add(item);  
  11. }   
Now this is the code that works just fine once, but crashes with the above error if I select a second record:
  1. private void listView1_SelectedIndexChanged(object sender, EventArgs e)  
  2. {  
  3. string lvname = listView1.SelectedItems[0].SubItems[0].Text;  
  4. string lvnumber = listView1.SelectedItems[0].SubItems[1].Text;  
  5. string lvdate = listView1.SelectedItems[0].SubItems[2].Text;  
  6. textBox2.Text = lvname;  
  7. textBox1.Text = lvnumber;  
  8. dateTimePicker1.Text = lvdate;  
  9. }   
Any suggestions would be appreciated, 
 
Thank you!

Answers (2)