簡體   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