Reputation: 31
I'm using the following code to bind a datagridview to a SQL Server database
POSfinalEntities dbe = new POSfinalEntities();
BindingSource bs = new BindingSource();
dataProducts.DataSource = null;
bs.DataSource = dbe.Book.ToList();
dataProducts.DataSource = bs;
It works okay. If I try to update the database, the database itself updates just fine. The problem is the datagridview. It doesn't show the changes. I've been trying for hours just to make it work and failed.
I tried setting the datasource = null and set it to datasource = bs again. I tried this.datagridview.refresh, nope.
I can't find a working solution to this. I'm sorry if it's a duplicate question but i tried every solution I can find in this site. If it's a duplicate. Could you at least provide a link to a WORKING solution. I'm really desperate. thanks.
Update: Here is the code I use to update the database values. I know, concatenation is bad practice, but it isn't the issue.
private void btneUpdate_Click(object sender, EventArgs e)
{
if (MessageBox.Show("You are about to save the changes. You won't be able to undo those changes.", "Update fields", MessageBoxButtons.OKCancel) == DialogResult.OK)
{
eprice = Convert.ToString(numericUpDown3.Value);
estock = Convert.ToString(numericUpDown4.Value);
con.Open();
cmd = new SqlCommand(@"UPDATE Book
SET BookTitle = '" + txteTitle.Text
+ "', BookAuthorLname = '" + txteAuthorLname.Text
+ "', BookAuthorFname = '" + txteAuthorFname.Text
+ "', BookPrice = '" + Convert.ToDecimal(eprice)
+ "', BookDescription = '" + txteDesc.Text
+ "', DatePublication = '" + dtpePublished.Value.Date
+ "', BookStock = '" + Convert.ToInt32(estock)
+ "', isFiction = '" + checkboxbool
+ "', GenreID = '" + cmbeCategory.SelectedValue
+ "' WHERE ISBN = '" + txteISBN.Text + "';", con);
cmd.ExecuteNonQuery();
con.Close();
}
}
Upvotes: 1
Views: 4664
Reputation: 5771
You are binding to the list dbe.Book.ToList(). Hence your datagrid would only refresh, if you add items to that list. You should hold the list in a variable and update that list.
POSfinalEntities dbe = new POSfinalEntities();
BindingSource bs = new BindingSource();
dataProducts.DataSource = null;
List<Book> books = dbe.Book.ToList();
bs.DataSource = books;
dataProducts.DataSource = bs;
Now if you add a book to the List it should automatically refresh.
Book book = new Book();
books.Add(book);
A cleaner way of doing this would to bind to Local
bs.DataSource = dbe.Book.Local.ToBindingList();
Now if you add objects to dbe.Book, your DataGridView will get automatically updated.
Book book = new Book();
dbe.Book.Add(book);
Note: The method ToBindingList() is an extension method. You need to add the namespace System.Data.Entity to get access to this method.
Upvotes: 1