Reputation: 1802
I am trying to bind datagridview with entity Framework and want to save datagridview changes back to database. but no success. i did some research found below code as sol. but in my case it is not going to work. the post i viewed almost 3 years old. may be the below logic is outdated. any suggestion please. i am using EF5.
AmzEntities amz;
public SellerSettings()
{
InitializeComponent();
}
private void SellerSettings_Load(object sender, EventArgs e)
{
amz = new AmzEntities();
AmzEntities context = new AmzEntities();
context.Sellers.Load();
dataGridView1.DataSource = context.Sellers.Local.ToBindingList(); ;
}
private void buttonSave_Click(object sender, EventArgs e)
{
amz.SaveChanges();
}
Upvotes: 0
Views: 6321
Reputation: 193
DataContext db = new DataContext();
public SupliersForm()
{
InitializeComponent();
supliersDG.DataSource = db.Supliers.Local.ToBindingList();
db.Supliers.Load();
}
private void SaveBtn_Click(object sender, EventArgs e)
{
supliersDG.EndEdit();
db.SaveChanges();
}
Upvotes: 2
Reputation: 190
I don't know If you want to make an insertion or an update,
for example if you want to save (insert) a sellers name, you would need to call the sellers class and point to the name in the class sellers and finally tell the DbContext to save it
AmzEntities context = new AmzEntities();
Sellers _sellers = new Sellers();
_sellers.name= "Jhon Abdullah";
context.Sellers.Add(_sellers);
context.SaveChanges();
update would be a little different,
var updateQuery = (from sellers1 in context.Sellers
where Sellers.name== "Jhon Abdullah"
select sellers1).FirstOrDefault();
updateQuery.name = "Jack Abdullah";
ExEnt.SaveChanges();
to save de data from the datagridview you would need to find the data in the datagridview, can be done with the index and a GridViewRow, depend on your datagridview structure and where is it being accessed _rowCommand, etc.
Example in rowCommand
int index = Convert.ToInt32(e.CommandArgument);
GridViewRow gvRow = dataGridView1.Rows[index];
Label lblName = (gvRow.FindControl("lbl_name") as Label);
AmzEntities context = new AmzEntities();
Sellers _sellers = new Sellers();
_sellers.name= lblName.Text;
context.Sellers.Add(_sellers);
context.SaveChanges();
good luck!
Upvotes: 2