In order to find the right object to update you first need to find the object in the People
collection that matches the object selected in the ListView
.
Person i = People.FirstOrDefault(p => p.Name == ((ListView) sender).SelectedItems[0].Text);
PopulateEditData(i); // refer below for method...
This can only work if you have the MultiSelect
property set to false, otherwise you will need to get the right item from the collection of selected items.
As seen here: http://msdn.microsoft.com/en-us/library/system.windows.forms.listview.selecteditems(v=vs.110).aspx
Once you have the right Person
object, you will be able to retrieve and display the objects details in the text boxes:
private void PopulateEditData(Person selectedPerson)
{
textBox1.Text = selectedPerson.Name;
textBox2.Text = selectedPerson.Hometown;
textBox3.Text = selectedPerson.Address;
textBox4.Text = selectedPerson.Phone;
textBox5.Text = selectedPerson.Email;
textBox6.Text = selectedPerson.AdditionalInfo;
dateTimePicker1.Value = selectedPerson.Birthday;
textBox1.ReadOnly = true;
textBox2.ReadOnly = true;
textBox3.ReadOnly = true;
textBox4.ReadOnly = true;
textBox5.ReadOnly = true;
textBox6.ReadOnly = true;
dateTimePicker1.Enabled = false;
toolStripButton5.Enabled = true;
}
I would also suggest setting the selectPerson
as a property of your form or one of the classes available to it so it is a little easier to edit and save the data on the object.
For the removal part of the problem, use the SelectedPerson
property for the item to be removed.
private void button1_Click(object sender, EventArgs e)
{
if (SelectedPerson != null)
{
People.Remove(SelectedPerson);
this.listView1.Items.Clear();
foreach (var person in People)
{
this.listView1.Items.Add(person.ToString());
this.listView1.Sorting = SortOrder.Ascending;
}
this.listView1.Refresh();
this.button1.Enabled = false;
}
}