1. 程式人生 > >直接在DataGridView控制元件中修改資料

直接在DataGridView控制元件中修改資料

建立一個Windows應用程式,向窗體中新增一個DataGridView控制元件和兩個button控制元件。DataGridView控制元件用於顯示、修改資料,兩個button分別用於載入資料和將修改後的資料更新到資料庫中

程式碼如下

using System;
using System.Data;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace Test03
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        SqlConnection conn;
        SqlDataAdapter adapter;
        int intindex = 0;
        private void button1_Click(object sender, EventArgs e)
        {
            conn = new SqlConnection("server=MRC-8CF94303A82\\MRNET;database=db_16;uid=sa;pwd=111");
            SqlDataAdapter sda = new SqlDataAdapter("select * from tb_emp",conn);
            DataSet ds = new DataSet();
            sda.Fill(ds);
            dataGridView1.DataSource = ds.Tables[0];
            dataGridView1.RowHeadersVisible = false;
            for (int i = 0; i < dataGridView1.ColumnCount;i++ )
            {
                dataGridView1.Columns[i].Width = 84;
            }
            button1.Enabled = false;
            dataGridView1.Columns[0].ReadOnly = true;
        }
        private DataTable dbconn(string strSql)
        {
            if (conn.State == ConnectionState.Open)
                conn.Close();
            this.adapter = new SqlDataAdapter(strSql, conn);
            DataTable dtSelect = new DataTable();
            int rnt = this.adapter.Fill(dtSelect);
            return dtSelect;
        }
        private void button2_Click(object sender, EventArgs e)
        {
            if (dbUpdate())
            {
                MessageBox.Show("修改成功!");
            }
        }
        private Boolean dbUpdate()
        {
            string strSql = "select * from tb_emp";
            DataTable dtUpdate = new DataTable();
            dtUpdate = this.dbconn(strSql);
            DataTable dtShow = new DataTable();
            dtShow = (DataTable)this.dataGridView1.DataSource;
            dtUpdate.ImportRow(dtShow.Rows[intindex]);
            SqlCommandBuilder CommandBuiler;
            CommandBuiler = new SqlCommandBuilder(this.adapter);
            this.adapter.Update(dtUpdate);
            dtUpdate.AcceptChanges();
            return true;
        }

        private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            intindex = e.RowIndex;
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }
    }
}

執行結果
在這裡插入圖片描述
單擊載入資料,會出現與資料庫連線的表格