2012-10-22 126 views
1

在我的項目中,有兩個文本框txtNametxtPopulation和一個按鈕,btnClick。每當用戶點擊btnClick時,數據集dsDetails的「Population」列中的值應根據txtPopulation中的值進行更新,其中「Name」列等於txtName。我知道這可以使用rowfilterselect完成,但我不知道要在其中實現什麼。 請沒有LINQ如何更新數據集

enter image description here 目前,我做這樣的事情。(工作

for (int intCount = 0; intCount < dsDetails.Tables[0].Rows.Count; intCount++) 
{ 
    if (lblCountryName.Text.Equals(dsDetails.Tables[0].Rows[intCount][0].ToString())) 
    { 
     dsDetails.Tables[0].Rows[intCount][3] = txtPopulation.Text; 
    } 
} 

回答

8

你需要調用.AcceptChanges()您的DataTable使更改致力於收集,像這樣:

for (int intCount = 0; intCount < dsDetails.Tables[0].Rows.Count; intCount++) 
{ 
    if (lblCountryName.Text.Equals(dsDetails.Tables[0].Rows[intCount][0].ToString())) 
    { 
     dsDetails.Tables[0].Rows[intCount][3] = txtPopulation.Text; 
    } 
} 

dsDetails.Tables[0].AcceptChanges(); 

使用選擇行過濾

您可以通過使用.Select行篩選器,這樣你的目標列:

foreach (DataRow row in dsDetails.Tables[0].Select("Name = '" + txtName.Text + "'")) 
{ 
    row[3] = txtPopulation.Text; 
} 

dsDetails.Tables[0].AcceptChanges(); 
+0

@Mr_Green不好意思,有點倉促那裏,實際上並沒有回答你的問題。用行過濾器更新。 –

2
DataRow[] dr = dsDetails.Tables[0].Select("Something='"+lblCountryName.Text+"'"); 
if(dr.Length > 0) 
{ 
dr[0][0] = "ChangeValue";//Datarow is reference to datatable it will automatically update the datatable values 
} 
dsDetails.Tables[0].AcceptChanges(); 
+0

謝謝,這也工作。 –