datagridview 填充.编辑和删除

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Configuration;

namespace datagridview操作
{
    public partial class Form1 : Form
    {
        SqlDataAdapter com;
        DataSet dst;
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            string str = "select * from student_user";
            SqlConnection con = new SqlConnection("server=localhost;database=student;uid=sa;pwd=");
            com = new SqlDataAdapter(str, con);
            SqlCommandBuilder cb = new SqlCommandBuilder(com); //通过该语句生成相应的(insert into/update/delete Sql)
            dst = new DataSet();
            com.Fill(dst); //填充DST
            dataGridView1.DataSource = dst.Tables[0]; //绑定
        }

        private void BtnUpd_Click(object sender, EventArgs e)
        {
            //由于DataGridView已与DataSet绑定,对DataGridView的更改(添加/删除/更新)亦会自动改变DataSet

            //更新回数据库
            try {
            com.Update(dst);
            MessageBox.Show("数据更新成功!");

           this.Form1_Load(this, new System.EventArgs());  //加载窗体

         //不加载窗体的方法

          // dst.AcceptChanges(); //DST更新

          // com.Update(dst);
          // MessageBox.Show("数据更新成功!");
             }
            catch(Exception ee)
            {}
            finally{}
        }
        
    }
}

posted @ 2008-07-30 09:21  浪子の无悔  阅读(503)  评论(0编辑  收藏  举报