如何在两个现有列之间的数据集中插入列? [英] How does one insert a column into a dataset between two existing columns?

查看:149
本文介绍了如何在两个现有列之间的数据集中插入列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



作为一个例子,我有一个DataSet定义如下:

  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之间插入列。 p>

DataSet具有添加列的方法,但我似乎找不到插入一个的最佳方式。



我想写一些类似以下的内容...

  ... Columns.InsertAfter(column_2,column_3 ,typeof(string))

最终结果应该是一个数据集,以下列:
column_1 column_2 column_3 column_4



而不是:
column_1 column_2 column_4 column_3这是添加方法给我的支持



肯定有办法做这样的事情。



修改 ...只是想根据以下一些意见澄清我在使用DataSet的工作:


我从一个存储的
程序。然后,我必须向数据集
添加
附加列,然后将其转换为Excel
文档。我没有控制
存储的proc
返回的数据,所以我必须在
事实之后添加列。



解决方案

您可以使用 DataColumn.SetOrdinal()方法。

  DataSet ds =新的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));
//将列3设置为列4之前
ds.Tables [0] .Columns [3] .SetOrdinal(2);


I'm trying to insert a column into an existing DataSet using C#.

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

later on in my code I am wanting to insert a column between column 2 and column 4.

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

The end result should be a data set that has a table with the following columns: column_1 column_2 column_3 column_4

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.

Edit...Just wanting to clarify what I'm doing with the DataSet based on some of the comments below:

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.

解决方案

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

这篇关于如何在两个现有列之间的数据集中插入列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆