需求:資料表含 id, name, num 三欄,DataGridView 僅顯示 name, num,但點擊列時需用隱藏的 id 查詢詳細資料。
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 查詢詳細資料
}
}
SELECT name, num 會導致 id 不在 DataTable 中,後續無法取得。若極度精簡顯示資料,可在繫結時將 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 取得。