首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

C# DataGridView 實作資料庫 CRUD 完整範例

     編輯:關於C語言

專案架構

  • 資料庫:SQL Server `northwind` 範例資料庫 `region` 表(`regionid`、`regiondescription`)。
  • UI:`DataGridView` 繫結 `DataSet`,`SqlDataAdapter` 管理同步。

核心程式碼


using System;
using System.Data;
using System.Data.SqlClient;
using System.Windows.Forms;

namespace DataSource
{
    public partial class Form1 : Form
    {
        DataSet _ds = new DataSet();
        SqlConnection _conn;
        SqlDataAdapter _da;
        const string ConnStr = "server=.;database=northwind;uid=sa;pwd=sa";
        const string SelectSql = "select * from region";

        public Form1() { InitializeComponent(); }

        private void Form1_Load(object sender, EventArgs e)
        {
            _conn = new SqlConnection(ConnStr);
            _da = new SqlDataAdapter(SelectSql, _conn);
            _da.Fill(_ds, "table");
            dataGridView1.DataSource = _ds.Tables["table"].DefaultView;
        }

        // 新增
        private bool BtnInsert()
        {
            _da.InsertCommand = _conn.CreateCommand();
            _da.InsertCommand.CommandText = "insert into region(regionid, regiondescription) values(@id, @desc)";
            _da.InsertCommand.Parameters.Add("@id", SqlDbType.Int, 4, "regionid");
            _da.InsertCommand.Parameters.Add("@desc", SqlDbType.VarChar, 10, "regiondescription");
            return _da.Update(_ds) > 0;
        }

        // 刪除
        private bool BtnDelete()
        {
            _da.DeleteCommand = _conn.CreateCommand();
            _da.DeleteCommand.CommandText = "delete from region where regionid=@id";
            var p = _da.DeleteCommand.Parameters.Add("@id", SqlDbType.Int, 4, "regionid");
            p.SourceVersion = DataRowVersion.Original;
            _ds.Tables["table"].Rows[dataGridView1.CurrentRow.Index].Delete();
            return _da.Update(_ds) > 0;
        }

        // 修改
        private bool BtnUpdate()
        {
            _da.UpdateCommand = _conn.CreateCommand();
            _da.UpdateCommand.CommandText = "update region set regionid=@id, regiondescription=@desc where regionid=@oldid";
            _da.UpdateCommand.Parameters.Add("@id", SqlDbType.Int, 4, "regionid");
            _da.UpdateCommand.Parameters.Add("@desc", SqlDbType.VarChar, 10, "regiondescription");
            var p = _da.UpdateCommand.Parameters.Add("@oldid", SqlDbType.Int, 4, "regionid");
            p.SourceVersion = DataRowVersion.Original;
            return _da.Update(_ds) > 0;
        }

        // 按鈕事件
        private void button1_Click(object sender, EventArgs e) => MessageBox.Show(BtnInsert() ? "新增成功!" : "新增失敗!");
        private void button2_Click(object sender, EventArgs e) => MessageBox.Show(BtnDelete() ? "刪除成功!" : "刪除失敗!");
        private void button3_Click(object sender, EventArgs e) => MessageBox.Show(BtnUpdate() ? "修改成功!" : "修改失敗!");
    }
}

關鍵技術解析

  1. 參數對應:`Parameter` 建構子 `(name, type, size, sourceColumn)` 自動從 `DataRow` 取值,`SourceVersion.Original` 確保刪除/修改用舊鍵值。
  2. `DataGridView` 繫結:`DefaultView` 提供排序/篩選,不影響底層 `DataTable`。
  3. 刪除流程:先 `Row.Delete()` 標記為 `Deleted`,`Update` 時發送 `DeleteCommand`。
  4. 連線管理:`SqlDataAdapter` 內部自動開啟/關閉連線,簡單場景無需手動 `Open/Close`。

最佳實踐補充

  • 連線字串應放 `app.config`,避免硬編碼密碼。
  • 生產環境使用參數化預存程序,防 SQL 注入、效能更佳。
  • 異步 `FillAsync`/`UpdateAsync` 避免 UI 凍結。
  • 樂觀並發:`UpdateCommand` 加 `WHERE` 條件比對 `timestamp`/`rowversion`。
  • 考慮改用 Entity Framework Core / Dapper 簡化資料存取層。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved