Rows cannot be programmatically added to the DataGridView's rows
當控件被資料綁定時,無法以程式設計方式向 DataGridView 的行集合中添加行。
關于這個問題的解決方法,網上隻有以 dataTable / dataSet 做為資料源的解決辦法。
一是,不綁定。二是,在 dataTable 上用 AddNew 。第三種是新插入一行,在綁定。
我現在是以 LINQ 為資料源來綁定 dataGridView 的。不綁定的話,要寫很多代碼,第三種沒有測試,看描述,應該也是很麻煩。我想采取第二種,但是 LINQ 的結果不能直接轉換成 DataTable 或 DataSet (請參見:http://msdn.microsoft.com/en-us/vbasic/bb688086.aspx)
一開始想用 BindingSource ,但是給BindingSource設完DataSource 之後,忘了給DataGridView 設定 DataSource 了,看不到結果,誤以為用 BindingSource 不行。
搜不到解決辦法,真的有點絕望的感覺。最後索性在試一把 BindingSource ,這下沒有忘記給 DataGridView 設定 DataSource:
private void SetGd2(int catID,string catName){
gd2DefaultCatID = catID;
gd2DefaultCatName = catName;
gd2Bs = new BindingSource();
gd2Bs.DataSource = dc.QV_Supplier_Category_Map.Where(m => m.CategoryID == catID);
gd2.DataSource = gd2Bs;
}
private void gd2_DefaultValuesNeeded(object sender , DataGridViewRowEventArgs e) {
e.Row.Cells["CategoryName"].Value = gd2DefaultCatName;
e.Row.Cells["CategoryID"].Value = gd2DefaultCatID;
private void gd1_CellDoubleClick(object sender , DataGridViewCellEventArgs e) {
QV_Supplier_Category_Map newRow = (QV_Supplier_Category_Map)gd2Bs.AddNew();
newRow.CategoryID = gd2DefaultCatID;
newRow.SupplierCategory = gd1.Rows[e.RowIndex].Cells["CategoryName"].Value.ToString();
newRow.SupplierID = (int)gd1.Rows[e.RowIndex].Cells["SupplierID"].Value;
gd2.CurrentRow.Cells["CategoryName"].Value = gd2DefaultCatName;
gd2.CurrentRow.Cells["SupplierName"].Value = (string)gd1.Rows[e.RowIndex].Cells["SupplierName"].Value;
可以以程式方式新增行了!但是卻有另外一個問題, 用這種方法給 DataGridView 添加新行,DataGridView 的 DefaultValuesNeeded 這個事件沒有觸發。。。
本文轉自 h2appy 51CTO部落格,原文連結:http://blog.51cto.com/h2appy/289948,如需轉載請自行聯系原作者