使用者在文字方塊輸入關鍵字多次查詢,每次查詢結果(整行資料)需累積保存在記憶體中,最後統一處理或顯示。
// 表單層級宣告
private DataTable _accumulatedTable = null;
private void btnQuery_Click(object sender, EventArgs e)
{
string keyword = txtKeyword.Text.Trim();
if (string.IsNullOrEmpty(keyword)) return;
// 1. 執行查詢取得 DataTable(假設已有方法)
DataTable dtResult = QueryDatabase(keyword); // 回傳含欄位結構的 DataTable
if (dtResult == null || dtResult.Rows.Count == 0)
{
MessageBox.Show("查無資料");
return;
}
// 2. 初始化累積表(第一次查詢時複製結構)
if (_accumulatedTable == null)
{
_accumulatedTable = dtResult.Clone(); // 僅複製結構(欄位、型別、約束)
}
// 3. 將本次結果逐行匯入累積表
foreach (DataRow row in dtResult.Rows)
{
_accumulatedTable.ImportRow(row); // 複製資料行,保留型別
}
// 4. 繫結顯示(可選)
dataGridView1.DataSource = null;
dataGridView1.DataSource = _accumulatedTable;
}
// 清除累積
private void btnClear_Click(object sender, EventArgs e)
{
_accumulatedTable = null;
dataGridView1.DataSource = null;
}
| 容器 | 優點 | 缺點 | 適用場景 |
|---|---|---|---|
| DataTable | 自帶結構、支援繫結、可篩選/排序、可寫 XML/JSON | 記憶體佔用較大 | 需直接顯示於 Grid、匯出 Excel/XML |
| List<T> (POCO) | 型別安全、效能好、序列化快 | 需手動定義類別、Grid 繫結需轉換 | 後續業務邏輯處理、Web API 回傳 |
| DataSet | 可包含多表、關聯 | 過重 | 多表關聯查詢 |
| Session / 快取 | 跨請求共享 | Web 專用、需序列化 | 分頁、跨頁面累積 |