Updating Cells in a DataTable

て烟熏妆下的殇ゞ 提交于 2019-12-11 07:07:55

问题


I'm writing a small app to do a little processing on some cells in a CSV file I have. I've figured out how to read and write CSV files with a library I found online, but I'm having trouble: the library parses CSV files into a DataTable, but, when I try to change a cell of the table, it isn't saving the change in the table!

Below is the code in question. I've separated the process into multiple variables and renamed some of the things to make it easier to debug for this question.

Code

Inside the loop:

string debug1 = readIn.Rows[i].ItemArray[numColumnToCopyTo].ToString();
string debug2 = readIn.Rows[i].ItemArray[numColumnToCopyTo].ToString().Trim();
string debug3 = readIn.Rows[i].ItemArray[numColumnToCopyFrom].ToString().Trim();
string towrite = debug2 + ", " + debug3;
readIn.Rows[i].ItemArray[numColumnToCopyTo] = (object)towrite;

After the loop:

readIn.AcceptChanges();

When I debug my code, I see that towrite is being formed correctly and everything's OK, except that the row isn't updated: why isn't it working? I have a feeling that I'm making a simple mistake here: the last time I worked with DataTables (quite a long time ago), I had similar problems.

If you're wondering why I'm adding another comma in towrite, it's because I'm combining a street address field with a zip code field - I hope that's not messing anything up.

My code is kind of messy, as I'm only trying to edit one file to make a small fix, so sorry.


回答1:


The easiest way to edit individual column values is to use the DataRow.Item indexer property:

readIn.Rows[i][numColumnToCopyTo] = (object)towrite;

This isn't well-documented, but DataRow.ItemArray's get accessor returns a copy of the underlying data. Here's the implementation, courtesy of Reflector:

public object[] get_ItemArray() {
    int defaultRecord = this.GetDefaultRecord();
    object[] objArray = new object[this._columns.Count];
    for (int i = 0; i < objArray.Length; i++) {
        DataColumn column = this._columns[i];
        objArray[i] = column[defaultRecord];
    }
    return objArray;
}

There's an awkward alternative method for editing column values: get a row's ItemArray, modify those values, then modify the row to use the updated array:

object[] values = readIn.Rows[i].ItemArray;
values[numColumnToCopyTo] = (object)towrite;
readIn.Rows.ItemArray = values;



回答2:


use SetField<> method :

    string debug1 = readIn.Rows[i].ItemArray[numColumnToCopyTo].ToString();
    string debug2 = readIn.Rows[i].ItemArray[numColumnToCopyTo].ToString().Trim();
    string debug3 = readIn.Rows[i].ItemArray[numColumnToCopyFrom].ToString().Trim();
    string towrite = debug2 + ", " + debug3;
    readIn.Rows[i].SetField<string>(numColumnToCopyTo,towrite); 

    readIn.AcceptChanges();


来源:https://stackoverflow.com/questions/2448510/updating-cells-in-a-datatable

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