//保存按钮 private void btnSave_Click(object sender, EventArgs e) { if (isCreate) { //创建联系人 Person person = new Person() { Name = txtName.Text.Trim(), DayOfBirth = dtpDayOfBirth.Value, Phone = txtPhone.Text.Trim() }; ContactsBook.Add(person); isCreate = false; } else//保存编辑后的信息 { if (listView1.SelectedItems.Count > 0) { Person person = new Person()//创建联系人 { ID = (listView1.SelectedItems[0].Tag as Person).ID, Name = txtName.Text.Trim(), DayOfBirth = dtpDayOfBirth.Value, Phone = txtPhone.Text.Trim() }; ContactsBook.Save(person); } } BindToListView(); OnBtnSaveClick(); }
// 清空按钮 private void btnRemoveAll_Click(object sender, EventArgs e) { if (MessageBox.Show("你真的要清空通讯录?", "清空?", MessageBoxButtons.YesNo) == DialogResult.Yes) { ContactsBook.RemoveAll(); BindToListView(); } }
//删除按钮 private void btnRemove_Click(object sender, EventArgs e) { if (listView1.SelectedIndices.Count > 0) { ContactsBook.Remove((Person)(listView1.SelectedItems[0].Tag)); BindToListView(); } else { MessageBox.Show("请先选中一条记录再删除"); } }
//读取所有联系人记录填充ListView void BindToListView() { listView1.Items.Clear(); foreach (Person p in ContactsBook.GetAll()) { ListViewItem item = new ListViewItem(p.Name); item.SubItems.Add(new ListViewItem.ListViewSubItem(item, p.DayOfBirth.ToLongDateString())); item.SubItems.Add(new ListViewItem.ListViewSubItem(item, p.Phone)); item.Tag = p;//将联系人对象的引用缓存在Tag中 listView1.Items.Add(item); } }