.net 直接在DataGridView控件中修改单元格数据,并保存到数据库

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

 

posted @ 2024-05-23 10:58  龙卷风吹毁停车场  阅读(793)  评论(0)    收藏  举报