萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 資料庫 >> MySQL 教學

C# ComboBox 繫結 SQL Server 日期欄位不重複年份

WinForms 應用常見需求:從 SQL Server 日期型別欄位提取不重複年份,繫結至 ComboBox 供使用者篩選。本文提供完整資料存取與 UI 繫結程式碼。

核心 SQL

SELECT DISTINCT YEAR(date_column) AS yr
FROM education_train
ORDER BY yr DESC;
  • YEAR() 函數擷取年份整數。
  • DISTINCT 去重。
  • DESC 讓最新年份在最上方。

完整 C# 實作

private void Education_Training_Load(object sender, EventArgs e)
{
    using (var db = new MyDBase(DBUser.sserver, DBUser.DBName, DBUser.suser, DBUser.spasswd))
    {
        // 1. 取得年份資料集
        DataSet ds = db.GetRecordset(
            "SELECT DISTINCT YEAR(date) AS yr FROM education_train ORDER BY yr DESC");

        if (db.ErrorCode())
        {
            MessageBox.Show(db.ErrMessage(), "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
            return;
        }

        if (ds.Tables[0].Rows.Count == 0) return;

        // 2. 繫結 ComboBox
        comboBox_Year.DataSource = ds.Tables[0];
        comboBox_Year.DisplayMember = "yr";   // 顯示年份
        comboBox_Year.ValueMember = "yr";     // 實際值同為年份

        // 3. 預設選中最大年份(最新)
        comboBox_Year.SelectedIndex = 0;  // 已 DESC 排序,索引 0 即最大

        // 4. 同步顯示於 DataGridView(示範用)
        dataGridView1.DataSource = ds.Tables[0];
    } // using 確保連線釋放
}

關鍵點說明

  • MyDBase 為自訂資料存取包裝類,內部封裝 SqlConnection/SqlDataAdapter。
  • GetRecordset 回傳 DataSet,適用於離線資料繫結。
  • DisplayMember/ValueMember 均指向別名 yr,簡化後續取值:comboBox_Year.SelectedValue 直接得 int 年份。
  • 錯誤處理:db.ErrorCode() 檢查執行狀態,彈窗提示。

進階:參數化查詢防注入

string sql = "SELECT DISTINCT YEAR(@dateCol) AS yr FROM @tbl ORDER BY yr DESC";
// 需動態 SQL 或預存程序,因識別符無法參數化
// 建議:預存程序 sp_GetDistinctYears @TableName, @DateColumn

擴充:多欄位篩選連動

若需「選年份 → 顯示該年月份」,可在 SelectedIndexChanged 事件中依 SelectedValue 重新查詢月份並繫結第二個 ComboBox。

此模式可直接套用至任何「日期欄位 → 年份/月份/季度」下拉選單場景。

copyright © 萬盛學電腦網 all rights reserved