详细内容
DataGridView中修改后的数据保存到数据库的方法
发布日期:2010-07-03     点击:5597     字体:[ ]

namespace DategridviewToSQL
{
    public partial class Form1 : Form
    {
        private DataTable DT = new DataTable();
        private SqlDataAdapter SDA = new SqlDataAdapter();
        private Boolean isUpdate = false;
       
       
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            load();
        }

        private void load()
        {

           //连接数据库
            SqlConnection conn = new SqlConnection(@"server = (local)\SQL2005;Integrated Security = true;" + "DataBase = test1");
            SqlCommand SCD = new SqlCommand("select * from aaa ", conn);
            SDA.SelectCommand = SCD;
            SDA.Fill(DT);
            dataGridView1.DataSource = DT;
        }

        private void button1_Click(object sender, EventArgs e)
        {

            if (isUpdate)
            {
                try
                {

                    //执行更新
                    SqlCommandBuilder SCB = new SqlCommandBuilder(SDA);
                    SDA.Update(DT);

                    isUpdate = false;
                }
                catch (System.Exception ex)
                {
                    MessageBox.Show(ex.ToString());
                    return;
                }
                MessageBox.Show("更新成功! ");
            }
            else
            {
                MessageBox.Show("没有更新内容! ");
            }

            for (int i = 0; i < DT.Rows.Count; i++)
                for (int j = 0; j < DT.Columns.Count; j++ )
                {
                    dataGridView1[j, i].Style.BackColor = Color.White;
                }

           
        }

        private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {

            //DataGridView单元格中值变化时变换背景颜色
            isUpdate = true;

            dataGridView1[e.ColumnIndex,e.RowIndex].Style.BackColor = Color.Blue;

           
        }

用户评论
昵称:匿名 来自:121.79.144.*  
2011/5/18 11:05:11
gdsgsdfg
昵称:匿名 来自:221.131.136.*  
2010/9/19 9:32:09
不行啊
昵称 
内容  *
验证码   
   
Copyright © 2010 zdbase.com All Rights Reserved. 苏ICP备15039389号 可人软件设计