天天看点

C#编程-75:DataGridView直接修改数据库

using System;
using System.Data;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace DataGridViewUpdate
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
 
        private SqlConnection GetConnection()
        {
            //string constr = @"Server=(localdb)\Projects;integrated security=SSPI;Initial Catalog=NewDB";
            string constr=@"server=(localdb)\Projects;integrated security=sspi;database=company";
            SqlConnection sqlcon = new SqlConnection(constr);
            return sqlcon;       
        }
        private void BindData()
        {
             
            SqlConnection sqlcon = GetConnection();
            try
            {
                sqlcon.Open();
                string sql = "select * from clerk";
                SqlDataAdapter sqladp = new SqlDataAdapter(sql, sqlcon);
                DataTable table = new DataTable();
                sqladp.Fill(table);
                this.dataGridView1.AutoGenerateColumns = true;
                this.dataGridView1.EditMode = DataGridViewEditMode.EditOnEnter;
                this.dataGridView1.DataSource = table;
            }
            catch (Exception ex)
            {
 
                MessageBox.Show(ex.Message);
            }
            finally
            {
                sqlcon.Close();
            }
            
        }
        private void Form1_Load(object sender, EventArgs e)
        {
            BindData();
        }
 
        //同步更新数据库
        private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            SqlConnection sqlcon = GetConnection();
            string str1 = this.dataGridView1.Columns[e.ColumnIndex].HeaderText + "=N'" + this.dataGridView1.CurrentCell.Value.ToString()+"'";
            string str2 = this.dataGridView1.Rows[e.RowIndex].Cells[0].Value.ToString();
            try
            {
                sqlcon.Open();
                string sql = "update clerk set "+str1+ "where id="+str2;
                SqlCommand sqlcom=new SqlCommand(sql,sqlcon);
                sqlcom.ExecuteNonQuery();
                BindData();
                
            }
            catch (Exception ex)
            {
 
                MessageBox.Show(ex.Message);
            }
            finally
            {
                sqlcon.Close();
            }
        }
    }
}