C# WinForms 的 DataGridView 控制項中,如果有先顯示多筆資料,在點選某一筆資料修改後,重新查詢資料並刷新 DataGridView,回到原本被選取的那筆資料的位置
說的很長
其實就是查詢後定位回原本修改的筆資料列中
做法:
1.記錄使用者選取資料的關鍵值(例如ID)
2.執行修改與重新查詢
3.重新查詢資料後,找到對應的那筆資料並選取該列
4.SelectionChanged 要抽出另外處理邏輯,來填入欄位的值到 TextBox
// 假設你的資料有一個唯一識別的欄位叫 "ID"
private void dataGridView1_SelectionChanged(object sender, EventArgs e)
{
if (dataGridView1.CurrentRow != null)
{
selectedID = dataGridView1.CurrentRow.Cells["ID"].Value.ToString();
}
}
// 全域變數記錄選取的ID
string selectedID = "";
private void ReloadDataAndRestoreSelection_GV1(string selectedID)
{
foreach (DataGridViewRow row in dataGridView1.Rows)
{
if (row.Cells["ID"].Value.ToString() == selectedID)
{
row.Selected = true;
dataGridView1.CurrentCell = row.Cells[0];
dataGridView1.FirstDisplayedScrollingRowIndex = row.Index;
// 手動呼叫 SelectionChanged 的處理邏輯
HandleRowSelectionChanged(row); // ← 把原本的 SelectionChanged 抽出來變一個方法
break;
}
}
}
private void dataGridView1_SelectionChanged(object sender, EventArgs e)
{
if (dataGridView1.CurrentRow != null)
{
HandleRowSelectionChanged(dataGridView1.CurrentRow);
}
}
private void HandleRowSelectionChanged(DataGridViewRow row)
{
// 原本的內容寫這裡,例如填入欄位的值到 TextBox 等
}
自我LV~