C# 如何通过获取数据表对象的行索引来更新数据表中的数据行?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8794002/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 04:28:18  来源:igfitidea点击:

How to update a datarow in datatable by getting rowindex of datatable object?

c#

提问by Ritzel

Basically, what I need to do is update a record in my datatable without knowing what the row index is. So I get the row index by searching the value in the columns of the datatable.

基本上,我需要做的是在不知道行索引是什么的情况下更新数据表中的记录。所以我通过搜索数据表列中的值来获得行索引。

I have searched over the internet but I can't understand why the code I have now only updates only the FIRST record in the datatable even when the value I'm searching for it is in the second row. What am I doing wrong?

我已经在互联网上进行了搜索,但我不明白为什么我现在拥有的代码只更新数据表中的第一个记录,即使我正在搜索它的值在第二行。我究竟做错了什么?

    private void SaveBtn__Click(object sender, EventArgs e)
    {
        if (SUpdateReq_Grd.SelectedRows.Count > 0)
        {
            if (MySkills_dataTable.Rows.Count > 0)
            {
                 string SkillID = SkillID_Txt.Text;
                 string Proficiency = Proficiency_Cmb.SelectedItem.ToString();
                 string Yrs_Exp = YrsExperience_cmb.SelectedItem.ToString();

                 //find rowIndex of skill id    
                 DataRow[] Rows = MySkills_dataTable.Select("SkillID='"+ SkillID + "'");

                MySkills_dataTable.Rows[0]["Proficiency"] = Proficiency;
                MySkills_dataTable.Rows[0]["Yrs_Experience"] = Yrs_Exp;

                MySkills_dataTable.AcceptChanges();
            }
        }
    }

采纳答案by Raf

I think you should use your Rowsvariable to set the new values on, and not the complete datatable:

我认为您应该使用Rows变量来设置新值,而不是完整的数据表:

//find rowIndex of skill id    
DataRow[] Rows = MySkills_dataTable.Select("SkillID='"+ SkillID + "'");

Rows[0]["Proficiency"] = Proficiency;
Rows[0]["Yrs_Experience"] = Yrs_Exp;