繁体   English   中英

将datagrid视图更改保存到数据库实体框架

[英]save datagrid view changes to database entity framework

我正在尝试将datagridview与实体Framework绑定,并想将datagridview的更改保存回数据库。 但没有成功。 我做了一些研究,发现下面的代码为sol。 但就我而言,它是行不通的。 我查看了将近3岁的帖子。 可能是以下逻辑已过时。 任何建议。 我正在使用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();
        }

我不知道如果您要插入或更新,

例如,如果您想保存(插入)卖方名称,则需要调用卖方类并指向卖方类别中的名称,最后告诉DbContext保存它

        AmzEntities context = new AmzEntities();
        Sellers _sellers = new Sellers();
        _sellers.name= "Jhon Abdullah";
        context.Sellers.Add(_sellers);
        context.SaveChanges();

更新会有所不同,

        var updateQuery = (from sellers1 in context.Sellers 
                           where Sellers.name== "Jhon Abdullah"
                           select sellers1).FirstOrDefault();
        updateQuery.name = "Jack Abdullah";
        ExEnt.SaveChanges();

要从datagridview中保存数据,您需要在datagridview中找到数据,可以使用索引和GridViewRow来完成,具体取决于您的datagridview结构以及在何处访问_rowCommand等。

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

祝好运!

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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