2014-04-03 44 views
0

我很新的C#,所以我希望得到綁定到數據庫中的Windows窗體上稍加點撥。下面是有關創建新項目主的一般流程:C#Windows窗體束縛datagridview的更新和​​保存

1)審查需要一個新行的未結銷售訂單。我使用一個列表視圖顯示項目編號和說明。在SelectedIndexChanged上,我使用與通過一個數據源添加的項目有關的數據來填充一些未啓用的行。還有一行被添加到DataGridView中,並使用不同的數據源以編程方式分配「默認」值。

上述工程偉大的...

2)用戶會再修改默認的建議,並保存網頁和數據應該被提交到數據庫。

的承諾有問題....

我將在這裏代碼解析出的作品的東西,相應的部分拉...

查找行工藝:

listView1_SelectedIndexChanged(...) 
    { 

     itemSelected.Text = listView1.SelectedItems[0].Text; 

     //Fill by item - use different datasets avoiding key conflicts 
     this.itemTableAdapter.FillByItem(this.COMPANY01DataSet.item, itemSelected.Text); 
     this.headerTableAdapter.FillByItem(this.itemDataSet.header, itemSelected.Text); 

     /// Assign default values as suggestions 
     this.PopHdrDGV(); 
    } 

分配默認值&所需的數據:

private void PopHdrDGV() 
    { 
     // set defaults as suggestions 
     DataRow hdrRow = itemDataSet.header.NewheaderRow(); 
     hdrRow["business_unit"] = "US01"; 
     hdrRow["item"] = "item to add"; 
     hdrRow["revision"] = "revision to add"; 
     hdrRow["qty"] = 10; 
     hdrRow["uom"] = "EA"; 
     hdrRow["cost_flag"] = false; 
     hdrRow["planning_flag"] = false; 
     hdrRow["eff_status"] = "N"; 
     hdrRow["eff_date"] = DateTime.Now; 
     hdrRow["created_by"] = Environment.UserName; 
     hdrRow["created_date"] = DateTime.Now; 
     hdrRow["changed_by"] = Environment.UserName; 
     hdrRow["changed_date"] = DateTime.Now; 

     //rebind to dgv 
     headerBindingSource.DataSource = hdrRow; 
     headerDataGridView.DataSource = headerBindingSource; 
    } 

保存DGV,並致力於數據庫:

button1_click(....) 
    { 
     Validate(); 
     headerBindingSource.EndEdit(); 
     headerTableAdapter.Update(itemDataSet.header); 
     headerDataGridView.Update(); /// added to test a few different approaches 
    } 

我知道這是一個非常基本的流程,但在我進行我沒有發現任何東西了所有的研究。感謝所有幫助。

回答

0

如果您正在使用MSSQL數據庫,我建議的DataTableDataAdapter的方法:

SqlDataAdapter adt = new SqlDataAdapter(PredefinedSqlCommand); 
     DataTable MyDataTable = DataGrid.DataSource as DataTable; 
     adt.Update(MyDataTable); 
     MyDataTable.AcceptChanges(); 

這一點,你必須表列綁定到的SqlCommand,並宣佈它作爲適配器的InsertCommand之前。同樣的方法是更新和刪除行。

祝你好運。