The Below code is updating the record but not reflecting it inside the Datagrid. What should I add to the update function to reflect the changes instantly after the update message?
Xaml Code
<Button Command="{Binding CmdUpdateUser}" Content="Update User"/>
ViewModel File
private void UpdateUser()
{
try
{
con = new SqlConnection(connectionString);
con.Open();
cmd = new SqlCommand($"UPDATE Customer " +
$"SET Id='{Id}',Name='{Name.ToString()}'," +
$"Age='{Age}',Country='{Country.ToString()}'," +
$"Active='{Convert.ToBoolean(Active)}'" +
$" WHERE Id='{Convert.ToInt32(SelectedCustomer.id)}'",con);
int n=cmd.ExecuteNonQuery();
if (n > 0)
{
MessageBox.Show("Update Successful");
}
Customer current = customer.Where(x => x.id == SelectedCustomer.id).FirstOrDefault();
current.id =Id;
current.name =Name;
current.age = Age;
current.country = Country;
current.active = Active;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
finally
{
con.Close();
}
}
The Customer
class should implement INotifyPropertyChanged and raise change notifications in the setters of the Id
, Name
, Age
, Country
and Active
properties:
public class Customer : INotifyPropertyChanged
{
private string _name;
public string Name
{
get { return _name; }
set { _name = value; OnPropertyChanged(); }
}
//+ the same for the rest of the properties
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null) =>
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}