EF 4.0 Datagridview not update

YHTAN

I am using EntityFramework. The DELETE function will delete the selected customer and refresh the datagridview, but the ADD function did not refresh the datagridview with the new added customer. Any idea?

public CustomerDialog()
{
    InitializeComponent();
    nw = new northwindEntities(); 
}

private void CustomerDialog_Load(object sender, EventArgs e)
{
    dgvCustomer.DataSource = nw.Customers;
}

private void btnDelete_Click(object sender, EventArgs e)
{
    string strSelectedCustomerID = getSelectedCustomerID();
    Customer customer = nw.Customers.Where(a => a.CustomerID == strSelectedCustomerID).First();
    nw.Customers.DeleteObject(customer);
    nw.SaveChanges();
}

//the  new customer is persist on the database, but the dgvCustomer is not update.
private void btnAdd_Click(object sender, EventArgs e)
{
    Customer newCustomer = new Customer() { 
            CustomerID = txtCustomerID.Text,
             CompanyName = txtCompanyName.Text,
             ContactName = txtContactName.Text
        };
    nw.Customers.AddObject(newCustomer);
    nw.SaveChanges();

    dgvCustomer.DataSource = nw.Customers ;
    dgvCustomer.Refresh();
}
Jens H
  1. You may try calling BindingSource.ResetBindings() method after you called the SaveChanges() method.

  2. Also, it could help to use a BindingList as the data source (see the article's code example how to use it).

  3. Ugly, but pragmatic approach: dgvCustomer.DataSource = null; dgvCustomer.DataSource = nw.Customers;

As a side note, dgvCustomer.Refresh() will not help you in this case. It does not refresh the data binding, it will cause the control to redraw itself in the UI, which most is likely not what you intended.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related