Windows Forms 資料繫結架構以 BindingContext、BindingManagerBase 管理資料指標,實現記錄導覽與 UI 同步。本文以 Access 2000 / SQL Server 2000 為例,完整示範連線、填充 DataSet、導覽 (首/尾/上/下)、刪除記錄的實作細節。
db.mdb、遠端 SQL Server: Server1/Data1person:id(數字)、xm(姓名)、xb(性別)、nl(年齡)、zip(郵遞區號)
// 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 (總筆數)。
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 在**用戶端**建立,不佔用伺服器資源,大量請求不會癱瘓資料庫。Rows.Delete() + AcceptChanges())。
// 新增
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();
// 同樣需寫回資料庫
OleDbParameter,防止注入。InsertCommand/UpdateCommand/DeleteCommand 後,單一 adapter.Update(ds, "person") 即可批次同步。OleDbTransaction。SqlConnection/SqlDataAdapter,效能與功能優於 OleDb。掌握 BindingManagerBase 導覽與 DataSet 離線同步機制,是 WinForms 資料庫程式設計的核心基石。理解「資料庫操作」與「DataSet 同步」分離的概念,能避免常見的 UI 與資料不一致問題。現代開發建議搭配 BindingSource (2.0+) 簡化繫結管理,並考慮 Entity Framework 等 ORM 提升開發效率。