-3

I would like to have an edit function in my program. I am creating a phone book wherein I use list in saving data (no database yet). I would like to have an edit function whenever i click an item in the list but I do not know how to do it.

This is my code for adding:

Person contact = new Person();
private ObservableCollection<Person> person = new ObservableCollection<Person>(); 
person.Add(new Person() 
    { 
        Name = contact.Name, 
        Contact = contact.Contact, 
        ImagePath = contact.ImagePath, 
        Gender = contact.Gender 
    });

I used selection changed when determining the selected item in the list. A help would be greatly appreciated. Thanks!

CathalMF
  • 9,705
  • 6
  • 70
  • 106
Sarah
  • 135
  • 3
  • 19
  • You want to edit a record or you want add a new record? – Masoud Andalibi Mar 30 '17 at 14:37
  • 1
    Why not just add `contact`? `person.Add(contact);` – Hans Kesting Mar 30 '17 at 14:40
  • Explaining the setup and reasoning behind the entire process of creating, editing, deleting and updating records (especially when dealing with WPF and databinding) is a little bit steep for a single question / answer. You are on the right track by using an `ObservableCollection` though. – Timothy Groote Mar 30 '17 at 14:42
  • So you make the properties of that item observable and when you edit them in the UI, the backing fields will change too. – Matt Burland Mar 30 '17 at 14:42
  • I want to edit a existing record. Not add another record. I already did the add, what I want to do now is edit an existing record – Sarah Mar 30 '17 at 14:42
  • @Sarah the typical way to go about that in WPF is to create a separate control for editing the records. one that uses two-way bindings would be simplest to implement. Bind the `datacontext` of that control to the `SelectedItem` property of your list, and you should be set to go – Timothy Groote Mar 30 '17 at 14:44
  • your question is not clear,do you want add a new record? – zahrakhani Dec 21 '20 at 19:33

2 Answers2

1

You should add an ID to your list, it will make your life easier, anyway here's mine from my previous assignment.

var vPersonID = YourListGoesHere.Where(pID => pID.personID == id).FirstOrDefault()
if (vPersonID !=null)
{
 vPersonID.Name = "ganda mo po";
//etc etc.
}

more info here Best way to update an element in a generic List .

Community
  • 1
  • 1
Google0593
  • 59
  • 13
0

You could use a DataGrid control to display and edit a collection of objects: https://msdn.microsoft.com/en-us/library/system.windows.controls.datagrid(v=vs.110).aspx

Set the ItemsSource property of the DataGrid to your ObservableCollection<Person> and double click in a cell to edit a value of a property of a Person object:

private ObservableCollection<Person> person = new ObservableCollection<Person>(); 
...
dataGrid.ItemsSource = person;

<DataGrid x:Name="dataGrid" />
mm8
  • 163,881
  • 10
  • 57
  • 88