我可以添加一行到数据集的中间使用c#

本文关键字:数据集 中间 一行 添加 我可以 | 更新日期: 2023-09-27 18:14:04

是否可以用c#在现有数据集的中间添加一行?我做了很多搜索,但没有找到任何关于如何做到这一点的东西。我试过什么?我试着搜索了很多,没有发现任何像数据集的'insertAt'方法。谢谢迈克

我可以添加一行到数据集的中间使用c#

数据集由数据表对象的集合组成所以我假设你在谈论一个数据表,对吗?如果是,它有一个InsertAt方法:

DataTable dt = dataset.Tables[0]; //Get first datatable from dataset
DataRow row = dt.NewRow();
//fill row
dt.Rows.InsertAt(row,3); //Insert at index 3

数据集没有行集合,所以你根本不能向它添加行。

您可以使用DataTable.Rows.InsertAt(row, i)通过索引插入一行到DataTable对象。如果表在DataSet中,则语法为DataSet.Tables[i].Rows.InsertAt(row, 0)

在我看来(虽然这可能需要很多时间),你可以创建一个数组或列表数组,然后通过for循环或任何循环从你的数据集传输所有的数据…然后在里面放一个if语句来检查你想把额外的数据放在哪里,像这样:

List<string> arrayList = dataset;// i know this is not possible just showing you that you have to put all your data from dataset to array:)
List <string> newList = new List<string>();//its up to you if you want to put another temporary array or you could simply output your data from the loop.
//THE LOOP
for(int i = 0; i<=arrayList.Count(); i++){
    if(i == x)//x is the index or you may change this statement its up to you
  {
    //do the print or pass the data to newList
      newList.add(arraList[i]);//not sure about this. its been a while since the last time i use this array list..
  }
}

另一种方法是自定义您的查询(如果您从数据库中提取一些数据)

快乐编码:)

下面是一个简短的示例:

class Program
{
    static void Main(string[] args)
    {
        DataSet ds = new DataSet();
        DataTable dt = ds.Tables.Add("Table");
        dt.Columns.Add("Id");
        for (int i = 0; i < 10; i++)
        {
            dt.Rows.Add(new object[]{i});
        }
        var newRow=dt.NewRow();
        newRow.ItemArray=new string[]{(dt.Rows.Count/2).ToString()+".middle"};
        dt.Rows.InsertAt(newRow, dt.Rows.Count / 2);
    }
}