首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

SQL 查詢隱藏特定欄位但保留可用性:前端顯示與後端查詢分離

     編輯:程式設計綜合問答

需求:資料表含 id, name, num 三欄,DataGridView 僅顯示 name, num,但點擊列時需用隱藏的 id 查詢詳細資料。

正確做法:DataGridView 隱藏欄位而非 SQL 隱藏

SQL 查詢照常 SELECT id, name, num FROM table,資料繫結後在前端隱藏 id 欄:

dataGridView1.DataSource = dt; // dt 含 id, name, num
dataGridView1.Columns["id"].Visible = false; // 隱藏顯示,資料仍在 Row 中

// 點擊事件取得 id
private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e) {
    if (e.RowIndex >= 0) {
        int id = Convert.ToInt32(dataGridView1.Rows[e.RowIndex].Cells["id"].Value);
        // 用 id 開啟 Form2 查詢詳細資料
    }
}

為什麼不在 SQL 隱藏?

  • SQL SELECT name, num 會導致 id 不在 DataTable 中,後續無法取得。
  • 資料繫結機制需完整主鍵支援更新/刪除操作。

替代方案:Tag 屬性攜帶主鍵

若極度精簡顯示資料,可在繫結時將 id 存入 Row.Tag:

foreach (DataGridViewRow row in dataGridView1.Rows) {
    row.Tag = row.Cells["id"].Value;
}
dataGridView1.Columns["id"].Visible = false;

點擊時直接 (int)dataGridView1.Rows[e.RowIndex].Tag 取得。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved