問題描述
我正在嘗試使用 C# 在現(xiàn)有數(shù)據(jù)集中插入一列.
I'm trying to insert a column into an existing DataSet using C#.
作為一個例子,我有一個如下定義的數(shù)據(jù)集:
As an example I have a DataSet defined as follows:
DataSet ds = new DataSet();
ds.Tables.Add(new DataTable());
ds.Tables[0].Columns.Add("column_1", typeof(string));
ds.Tables[0].Columns.Add("column_2", typeof(int));
ds.Tables[0].Columns.Add("column_4", typeof(string));
稍后在我的代碼中,我想在第 2 列和第 4 列之間插入一列.
later on in my code I am wanting to insert a column between column 2 and column 4.
DataSet 有添加列的方法,但我似乎找不到插入列的最佳方法.
DataSets have methods for adding a column but I can't seem to find the best way in insert one.
我想寫一些類似下面的東西......
I'd like to write something like the following...
...Columns.InsertAfter("column_2", "column_3", typeof(string))
最終結(jié)果應該是一個包含以下列的表的數(shù)據(jù)集:column_1 column_2 column_3 column_4
The end result should be a data set that has a table with the following columns: column_1 column_2 column_3 column_4
而不是:column_1 column_2 column_4 column_3 這是 add 方法給我的
rather than: column_1 column_2 column_4 column_3 which is what the add method gives me
肯定有辦法做這樣的事情.
surely there must be a way of doing something like this.
編輯...只是想根據(jù)下面的一些評論澄清我對 DataSet 所做的事情:
Edit...Just wanting to clarify what I'm doing with the DataSet based on some of the comments below:
我正在從存儲的程序.然后我必須添加數(shù)據(jù)集的附加列然后將其轉(zhuǎn)換為 Excel文檔.我無法控制存儲過程返回的數(shù)據(jù)所以我必須在之后添加列事實.
I am getting a data set from a stored procedure. I am then having to add additional columns to the data set which is then converted into an Excel document. I do not have control over the data returned by the stored proc so I have to add columns after the fact.
推薦答案
您可以使用 DataColumn.SetOrdinal() 用于此目的的方法.
You can use the DataColumn.SetOrdinal() method for this purpose.
DataSet ds = new DataSet();
ds.Tables.Add(new DataTable());
ds.Tables[0].Columns.Add("column_1", typeof(string));
ds.Tables[0].Columns.Add("column_2", typeof(int));
ds.Tables[0].Columns.Add("column_4", typeof(string));
ds.Tables[0].Columns.Add("column_3", typeof(string));
//set column 3 to be before column 4
ds.Tables[0].Columns[3].SetOrdinal(2);
這篇關于如何將一列插入到兩個現(xiàn)有列之間的數(shù)據(jù)集中?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!