掌握改變記錄指標才能隨心所欲瀏覽記錄。Visual C# 透過 BindingManagerBase 物件實現,位於 System.Windows.Forms 命名空間。此抽象物件管理所有綁定的同類資料源與資料成員,主要用到兩個屬性:
Position:目前資料集的記錄指標Count:目前資料集的記錄總數四個按鈕對應程式碼:
// 首記錄
myBind.Position = 0;
// 尾記錄
myBind.Position = myBind.Count - 1;
// 下一條
if (myBind.Position == myBind.Count - 1)
MessageBox.Show("已經到了最後一條記錄!");
else
myBind.Position += 1;
// 上一條
if (myBind.Position == 0)
MessageBox.Show("已經到了第一條記錄!");
else
myBind.Position -= 1;
using System;
using System.Drawing;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data.OleDb;
using System.Data;
public class DataView : Form
{
// ... 元件宣告 ...
private System.Data.DataSet myDataSet;
private BindingManagerBase myBind;
public DataView()
{
GetConnected();
InitializeComponent();
}
public void GetConnected()
{
try
{
string strCon = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=sample.mdb";
OleDbConnection myConn = new OleDbConnection(strCon);
string strCom = "SELECT * FROM books";
myDataSet = new DataSet();
myConn.Open();
OleDbDataAdapter myCommand = new OleDbDataAdapter(strCom, myConn);
myCommand.Fill(myDataSet, "books");
myConn.Close();
}
catch (Exception e)
{
MessageBox.Show("連接錯誤! " + e.ToString(), "錯誤");
}
}
private void InitializeComponent()
{
// ... 元件初始化、版面配置 ...
// 關鍵:資料綁定
t_bookid.DataBindings.Add("Text", myDataSet, "books.bookid");
t_books.DataBindings.Add("Text", myDataSet, "books.bookstock");
t_booktitle.DataBindings.Add("Text", myDataSet, "books.booktitle");
t_bookprice.DataBindings.Add("Text", myDataSet, "books.bookprice");
t_bookauthor.DataBindings.Add("Text", myDataSet, "books.bookauthor");
// 綁定 BindingManagerBase
myBind = this.BindingContext[myDataSet, "books"];
}
// 按鈕事件處理器
protected void GoLast(object sender, EventArgs e) { myBind.Position = myBind.Count - 1; }
protected void GoNext(object sender, EventArgs e) { /* ... */ }
protected void GoPrevious(object sender, EventArgs e) { /* ... */ }
protected void GoFirst(object sender, EventArgs e) { myBind.Position = 0; }
}
本文重點在於如何改變資料集記錄指標,以及讓文字方塊隨指標變化動態顯示內容。雖然 C# 處理此類操作比其他語言稍顯麻煩,但對程式設計師更靈活,擁有更大發展空間。