Insert Update and Delete in C#
阿新 • • 發佈:2019-02-06
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace EF_Single { public partial class Form1 : Form { Customer model = new Customer(); public Form1() { InitializeComponent(); } private void btnSave_Click(object sender, EventArgs e) { model.FirstName = txtFirstName.Text.Trim(); model.LastName = txtLastName.Text.Trim(); model.City = txtCity.Text.Trim(); model.Address = txtAddress.Text.Trim(); using (testdb1Entities db = new testdb1Entities()) { if (model.CustomerID == 0) db.Customers.Add(model); else db.Entry(model).State = System.Data.Entity.EntityState.Modified; db.SaveChanges(); } Clear(); MessageBox.Show("Saved Successfully"); PopulateDataGridView(); } private void btnDelete_Click(object sender, EventArgs e) { if(MessageBox.Show("Are you sure to delete this record?","Delete Confirm", MessageBoxButtons.YesNo) == DialogResult.Yes) { using (testdb1Entities db = new testdb1Entities()) { var entry = db.Entry(model); if (entry.State == System.Data.Entity.EntityState.Detached) db.Customers.Attach(model); db.Customers.Remove(model); db.SaveChanges(); PopulateDataGridView(); Clear(); MessageBox.Show("Deleted Successfully"); } } } private void btnCancel_Click(object sender, EventArgs e) { Clear(); } void Clear() { txtFirstName.Text = txtLastName.Text = txtCity.Text = txtAddress.Text = ""; btnSave.Text = "Save"; btnDelete.Enabled = false; model.CustomerID = 0; } private void Form1_Load(object sender, EventArgs e) { Clear(); PopulateDataGridView(); } void PopulateDataGridView() { dgvCustomer.AutoGenerateColumns = false; using (testdb1Entities db = new testdb1Entities()) { dgvCustomer.DataSource = db.Customers.ToList<Customer>(); } } private void dgvCustomer_CurrentCellChanged(object sender, EventArgs e) { if(dgvCustomer.CurrentRow != null && dgvCustomer.CurrentRow.Index != -1 && dgvCustomer.CurrentRow.Cells["CustomerID"].Value !=null) { model.CustomerID = Convert.ToInt32(dgvCustomer.CurrentRow.Cells["CustomerID"].Value); using (testdb1Entities db = new testdb1Entities()) { model = db.Customers.Where(x=>x.CustomerID == model.CustomerID).FirstOrDefault(); if (model != null) { txtFirstName.Text = model.FirstName; txtLastName.Text = model.LastName; txtCity.Text = model.City; txtAddress.Text = model.Address; } } btnSave.Text = "Update"; btnDelete.Enabled = true; } } } }