How to update a dataset

≡放荡痞女 提交于 2019-12-19 11:40:14

问题


In my project, there are two textBoxes, txtName and txtPopulation and a Button, btnClick. whenever the user clicks btnClick, the value in the "Population" column of the dataset dsDetails should get updated by the value in txtPopulation, where the "Name" Column is equal to txtName. I know this can be done using rowfilter or select but I have no idea what to implement in it. Please no linq

Currently, I am doing something like this..(working)
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;
    }
}

回答1:


You need to call .AcceptChanges() on your DataTable so your changes are committed to the collection, like this:

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

Using select row filter

You can target your column by using the .Select row filter, like this:

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

dsDetails.Tables[0].AcceptChanges();



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


来源:https://stackoverflow.com/questions/13008748/how-to-update-a-dataset

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!