开发者

.Net DataTable column export

Im looking to get a column and all its row data from a DataTable object then create a new column in another data table and append it with the new column and its rows. The issue I keep encountering is the row data will come out, as will the column names, but all of the rows are appended to the same column, I'm sure im missing something obvious, infact I know I am! Any help is greatly appriciated.

    void GetColumns()
    {
        // add the columns to the new datatable
        foreach (int i in mapValues开发者_开发问答)
        {
            SplitData.Columns.Add(i.ToString());
        }
        // map values contains the index numbers of my target columns
        foreach (int x in mapValues)
        {

            foreach (DataRow row in OrigData.Rows)
            {
                SplitData.Rows.Add(row[mapValues[LocalIndex]]);
            }

            LocalIndex++;
        }
    }


The DataRow.Add overload that you are using is the params one, so you are just putting your orig column data in the first column of the new DataTable.

You probably want something like:

DataRow newRow = SplitData.NewRow(); // gets a new blank row with the right schema
newRow[x.ToString()] = row[mapValues[LocalIndex]; // sets the column (that you created before) to the orig data
SplitData.Rows.Add(newRow);

as the core of your second for loop. You might as well do it in one loop too.


Although the accepted answer was totally right and I learned something from it, it turns out the DataTable.ImportRow method is exactly what I want for my needs, so just for future reference for anyone who might stumble upon this.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜