Deleting a list entry based on listview selection

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Scalp994
    New Member
    • Feb 2012
    • 8

    Deleting a list entry based on listview selection

    Hey there!

    I have a class called "student" which consists of a string "surname" and a string array "subjects". I also have a list of type "student" of all the students.

    Code:
    public class student
            {
                public static string surname;
                public string[] subjects = new string[10];
            };
    
            List<student> students = new List<student>();
    I have a button that adds a given student to the listview and creates a new object in the list. Let's say it works like this:
    Code:
     private void button1_Click(object sender, EventArgs e)
            {
                ListViewItem lvi = new ListViewItem(textBox1.Text);
                lvi.SubItems.Add(subjects1);
    listView1.Items.Add(lvi);
    
    
     students.Add(new student
                {
                    nazwisko = textBox1.Text,
                    subjects1 = subjects
                });
    }
    I'm now trying to add a code that, upon clicking on a contextmenustri p on the listview, would delete the student from BOTH the listview and the students LIST.

    Code:
    //upon clicking the remove button on a selected listview item
    if (listView1.SelectedItems.Count != 0)
                {
                    foreach (ListViewItem lvi in listView1.SelectedItems)
                    {
                        
                        lvi.Remove();
                    }
                }
    However, I can't figure out how to remove THE SAME student from the students LIST. It's because I'd need to know the index of the student I'm selecting on listview, or I'd need to get the value of surname based on the selection. Any ideas how I can pull it out?
  • Maraj
    New Member
    • Nov 2011
    • 24

    #2
    Try this
    Code:
     if (listView1.SelectedItems.Count != 0)
     3.             {
     4.                 foreach (ListViewItem lvi in listView1.SelectedItems)
                      {
       students.RemoveAt(listView1.Items.IndexOf(lvi));
                          lvi.Remove();
                      }
                  }

    Comment

    • Scalp994
      New Member
      • Feb 2012
      • 8

      #3
      Thanks a lot, it works like a charm now :)

      Comment

      Working...