1.获取datagridview单元格修改的内容
//单元格的值发生改变时触发事件 private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e) { //获取当前行绑定的内容 AppraisalBases item = (AppraisalBases)dataGridView1.Rows[e.RowIndex].DataBoundItem; //MessageBox.Show(item.BaseType); //获取到修改的值 AppraisalBases.Update(item); }
2. 定义 AppraisalBases.cs 内容
namespace Appraisal_System.Models { public class AppraisalBases { public int Id { get; set; } public string BaseType { get; set; } public int AppraisalBase { get; set; } public bool IsDel { get; set; } public static int Update(AppraisalBases rows) { string sql = "update AppraisalBases set BaseType=@BaseType,AppraisalBase=@AppraisalBase,IsDel=@IsDel where Id=@Id"; SqlParameter[] pars = { new SqlParameter("@BaseType", rows.BaseType), new SqlParameter("@AppraisalBase", rows.AppraisalBase), new SqlParameter("@IsDel",rows.IsDel), new SqlParameter("@Id",rows.Id), }; int count = SqlHelper.ExecuteNoQuery(sql, pars); return count; } } }
3. SqlHelper.cs 定义
using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Appraisal_System.Utility { public static class SqlHelper { public static string connStr { get; set; } public static DataTable ExecuteTable(string sql) { using (SqlConnection conn = new SqlConnection(connStr)) { conn.Open(); SqlCommand cmd = new SqlCommand(sql, conn); SqlDataAdapter adapter = new SqlDataAdapter(cmd); DataSet ds = new DataSet(); adapter.Fill(ds); return ds.Tables[0]; } } public static int ExecuteNoQuery(string sql, params SqlParameter[] pars) { using (SqlConnection conn = new SqlConnection(connStr)) { conn.Open(); SqlCommand cmd = new SqlCommand(sql, conn); cmd.Parameters.Clear(); cmd.Parameters.AddRange(pars); int count = cmd.ExecuteNonQuery(); if(count <= 0) { throw new Exception("数据库操作失败"); } return count; } } } }
标签:控件,cmd,单元格,System,DataGridView,new,using,public,AppraisalBases From: https://www.cnblogs.com/tlfe/p/18207898