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

C# 三層架構實作:表現層 (UI) 呼叫商業邏輯層範例 (第 2 部分)

     編輯:關於C語言

UI 程式碼片段 (WinForms)

僅展示呼叫 BLL 的事件處理,省略介面設計細節。

新增按鈕

private void cmdAdd_Click(object sender, EventArgs e)
{
    try
    {
        BOCustomer cus = new BOCustomer();
        cus.cusID = txtID.Text;
        cus.LName = txtLName.Text;
        cus.FName = txtFName.Text;
        cus.Tel = txtTel.Text;
        cus.Address = txtAddress.Text;
        cus.Add(); // 呼叫 BLL 新增
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
}

查詢按鈕

private void cmdFind_Click(object sender, EventArgs e)
{
    try
    {
        string id = txtID.Text;
        BOCustomer cus = new BOCustomer();
        DataSet ds = cus.Find(id); // BLL 回傳 DataSet

        if (ds != null && ds.Tables[0].Rows.Count > 0)
        {
            DataRow row = ds.Tables[0].Rows[0];
            txtFName.Text = row["CUS_F_NAME"].ToString();
            txtLName.Text = row["CUS_L_NAME"].ToString();
            txtAddress.Text = row["CUS_ADDRESS"].ToString();
            txtTel.Text = row["CUS_TEL"].ToString();
        }
    }
    catch (Exception ex) { MessageBox.Show(ex.Message); }
}

修改按鈕

private void cmdUpdate_Click(object sender, EventArgs e)
{
    try
    {
        BOCustomer cus = new BOCustomer();
        cus.cusID = txtID.Text;
        cus.LName = txtLName.Text;
        cus.FName = txtFName.Text;
        cus.Tel = txtTel.Text;
        cus.Address = txtAddress.Text;
        cus.Update(); // 呼叫 BLL 修改
    }
    catch (Exception ex) { MessageBox.Show(ex.Message); }
}

架構說明

  • UI 僅負責蒐集輸入、呼叫 BLL 方法、呈現結果,不含 SQL 或連線邏輯。
  • BLL 封裝業務規則 (如驗證、計算),再委派 DAL 執行資料操作。
  • 如此分層可單獨測試 BLL、更換資料庫不影響 UI。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved