简体   繁体   中英

save datagrid view changes to database entity framework

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();
        }

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!

    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();
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM