星期三, 6月 18, 2014

[C#] CurrencyManager

在公司內 VFP 系統內,都會有個自訂控制項,來作到第一筆、上一筆、下一筆和最後一筆,資料跳躍的功能,在 C# 中則是可以利用 CurrencyManager Class 來作到
CurrencyManager cm;
DataTable dt = new DataTable("CurrencyManagerDemo");

private void Form1_Load(object sender, EventArgs e)
{
    DBinit();
}

private void DBinit()
{
    dt = dtFill();
    cm = BindingContext[dt] as CurrencyManager;
    cm.PositionChanged += cm_PositionChanged;
    cm_EnableControl();
    txtPosition.Text = cm_PositionMessage();

    // DataBinding
    grdData.DataSource = dt;
    txtData.DataBindings.Add("Text", dt, "ID");
}

public DataTable dtFill()
{
    // 建立基本測試資料
    DataTable dt = new DataTable();
    dt.Columns.Add("ID", typeof(int));
    for (int i = 0; i < 5; i++)
    {
        dt.Rows.Add(i);
    }

    if (dt.PrimaryKey.Length == 0) dt.Constraints.Add("PK", dt.Columns["ID"], true);

    return dt;
}

#region CurrencyManager 相關
void cm_PositionChanged(object sender, EventArgs e)
{
    txtPosition.Text = cm_PositionMessage();
    cm_EnableControl(); 
}

private void btnFirst_Click(object sender, EventArgs e)
{
    cm.Position = 0;
}

private void btnPre_Click(object sender, EventArgs e)
{
    if (cm.Position > 0) cm.Position--;
}

private void btnNext_Click(object sender, EventArgs e)
{
    if (cm.Position < cm.Count - 1) cm.Position++;
}

private void btnLast_Click(object sender, EventArgs e)
{
    cm.Position = cm.Count - 1;
}

private void cm_EnableControl()
{
    btnFirst.Enabled = (cm.Position > 0);
    btnPre.Enabled = (cm.Position > 0);
    btnNext.Enabled = (cm.Position < cm.Count - 1);
    btnLast.Enabled = (cm.Position < cm.Count - 1);
}

private string cm_PositionMessage()
{
    return String.Format("{0} / {1}", (cm.Position + 1).ToString(), cm.Count);
}
#endregion

[ADO] CurrencyManager

CurrencyManager 為 dotNet 1.0 的功能,在 dotNet 2.0 用 BindingSource 搭配 BingingNavgatoe 來取代它,作出來後才發現這個殘酷事實,Orz ~~

沒有留言:

張貼留言