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

Visual C# 資料庫基礎程式設計:BindingManagerBase 導覽與 CRUD 完整實作

     編輯:關於C#

前言

Windows Forms 資料繫結架構以 BindingContext、BindingManagerBase 管理資料指標,實現記錄導覽與 UI 同步。本文以 Access 2000 / SQL Server 2000 為例,完整示範連線、填充 DataSet、導覽 (首/尾/上/下)、刪除記錄的實作細節。

環境與資料表結構

  • 本地 Access: db.mdb、遠端 SQL Server: Server1/Data1
  • 資料表 person:id(數字)、xm(姓名)、xb(性別)、nl(年齡)、zip(郵遞區號)

建立 BindingManagerBase


// Access 連線
string strCon = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=db.mdb";
OleDbConnection conn = new OleDbConnection(strCon);
string strCom = "SELECT * FROM person";
DataSet ds = new DataSet();
OleDbDataAdapter adapter = new OleDbDataAdapter(strCom, conn);
adapter.Fill(ds, "person");
conn.Close();

// 取得 BindingManagerBase
BindingManagerBase bind = this.BindingContext[ds, "person"];

SQL Server 連線字串調整為 Provider=SQLOLEDB.1;User ID=sa;Initial Catalog=data1;Data Source=server1,其餘邏輯相同。

記錄導覽實作


// 上一筆
private void GoPrevious(object sender, EventArgs e)
{
    if (bind.Position == 0)
        MessageBox.Show("已經是第一筆!");
    else
        bind.Position -= 1;
}

// 下一筆
private void GoNext(object sender, EventArgs e)
{
    if (bind.Position == bind.Count - 1)
        MessageBox.Show("已經是最後一筆!");
    else
        bind.Position += 1;
}

// 第一筆
private void GoFirst(object sender, EventArgs e) => bind.Position = 0;

// 最後一筆
private void GoLast(object sender, EventArgs e) => bind.Position = bind.Count - 1;

關鍵屬性:Position (0-based 當前索引)、Count (總筆數)。

刪除記錄:同步資料庫與 DataSet


private void DeleteRecord(object sender, EventArgs e)
{
    DialogResult r = MessageBox.Show("確定刪除當前記錄?", "刪除確認", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
    if (r == DialogResult.Yes)
    {
        try
        {
            string strCon = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=db.mdb";
            using (OleDbConnection conn = new OleDbConnection(strCon))
            {
                conn.Open();
                // 1. 從資料庫刪除
                string sql = "DELETE FROM person WHERE id=" + txtId.Text;
                OleDbCommand cmd = new OleDbCommand(sql, conn);
                cmd.ExecuteNonQuery();

                // 2. 從 DataSet 刪除 (保持 UI 同步)
                ds.Tables["person"].Rows[bind.Position].Delete();
                ds.Tables["person"].AcceptChanges();
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show("刪除失敗:" + ex.Message);
        }
    }
}

核心觀念:DataSet 為離線容器

  • DataSet 在**用戶端**建立,不佔用伺服器資源,大量請求不會癱瘓資料庫。
  • 對資料庫的修改 (Insert/Update/Delete) **不會自動反映** 到 DataSet,必須手動同步 (如上例 Rows.Delete() + AcceptChanges())。
  • UI 控制項繫結的是 DataSet,不同步會導致「刪除卻還顯示」的假象。

進階補充:新增與修改


// 新增
DataRow newRow = ds.Tables["person"].NewRow();
newRow["xm"] = txtName.Text; newRow["xb"] = txtGender.Text; // ...
ds.Tables["person"].Rows.Add(newRow);
// 寫回資料庫需使用 OleDbDataAdapter.Update() 或手動 INSERT 指令

// 修改
DataRow row = ds.Tables["person"].Rows[bind.Position];
row["xm"] = txtName.Text; // ...
row.AcceptChanges();
// 同樣需寫回資料庫

最佳實務建議

  1. 參數化查詢:刪除/新增/修改 SQL 皆應使用 OleDbParameter,防止注入。
  2. 使用 DataAdapter.Update:設定 InsertCommand/UpdateCommand/DeleteCommand 後,單一 adapter.Update(ds, "person") 即可批次同步。
  3. 錯誤處理與交易:多筆操作需原子性時,使用 OleDbTransaction。
  4. 遷移至 SqlClient:SQL Server 專案請改用 SqlConnection/SqlDataAdapter,效能與功能優於 OleDb。

結語

掌握 BindingManagerBase 導覽與 DataSet 離線同步機制,是 WinForms 資料庫程式設計的核心基石。理解「資料庫操作」與「DataSet 同步」分離的概念,能避免常見的 UI 與資料不一致問題。現代開發建議搭配 BindingSource (2.0+) 簡化繫結管理,並考慮 Entity Framework 等 ORM 提升開發效率。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved