如何更新数据集

在我的项目中,有两个textBox, txtNametxtPopulation以及一个Button, btnClick 。 每当用户单击btnClick ,数据集dsDetails的“Population”列中的dsDetails应该通过txtPopulation的值更新,其中“Name”列等于txtName 。 我知道这可以使用rowfilterselect来完成,但我不知道在其中实现什么。 请不要linq

在此处输入图像描述 目前,我正在做这样的事情..( 工作

 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; } } 

您需要在DataTable上调用.AcceptChanges() ,以便将更改提交到集合,如下所示:

 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(); 

使用选择行filter

您可以使用.Select行filter来定位列,如下所示:

 foreach (DataRow row in dsDetails.Tables[0].Select("Name = '" + txtName.Text + "'")) { row[3] = txtPopulation.Text; } dsDetails.Tables[0].AcceptChanges(); 
 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();