手動構建 DataTable 並設定 PrimaryKey 為 StuID,但插入兩筆 StuID="09001" 的資料,導致 BindingSource 無法正確定位,TextBox 不顯示數據。
DataTable.PrimaryKey 要求唯一,重複插入相同主鍵值會拋出例外或導致索引器失效,BindingSource 內部依賴主鍵進行貨幣管理(Current/Position),主鍵衝突會使導航失效。
09003)。// dt.PrimaryKey = new DataColumn[] { dt.Columns[0] }; // 註釋掉DataTable dt = new DataTable("T_Student");
dt.Columns.Add("StuID", typeof(string));
dt.Columns.Add("Name", typeof(string));
// ... 其他欄位
// dt.PrimaryKey = new DataColumn[] { dt.Columns[0] }; // 若測試數據不唯一,請移除
dt.Rows.Add("09001", "王小玲", "女", 18, "軟件091");
dt.Rows.Add("09002", "張偉", "男", 20, "軟件092");
dt.Rows.Add("09003", "謝明明", "男", 19, "軟件091"); // 修正主鍵
BindingSource bs = new BindingSource();
bs.DataSource = dt;
txtNo.DataBindings.Add("Text", bs, "StuID");
// ... 其他綁定
BindingSource 支援排序、篩選、編輯狀態管理,善用 Filter/Sort 屬性可減少 SQL 查詢。