【问题标题】:Adding Datarow between Rows?在行之间添加数据行?
【发布时间】:2009-06-24 14:31:20
【问题描述】:

如何在数据表中的现有行之间添加行? 谢谢

【问题讨论】:

  • 你的意思是在中间?不附加!!?如果是,那为什么?
  • 是的在中间。我计算了一些数据,然后它们必须在中间添加

标签: c# datatable datarow


【解决方案1】:

dataTable.Rows.InsertAt(DataRow row, int position);


示例:

using System;
using System.Collections.Generic;
using System.Text;
using System.Data;

namespace ConsoleApplication1
{
    class Program
    {
        static DataTable getDataTable()
        {
            DataTable table = new DataTable();
            table.Columns.Add("userID", typeof(int));
            table.Columns.Add("userName", typeof(string));
            table.Columns.Add("isAwesome", typeof(bool));
            return table;
        }

        static DataRow getRow(DataTable table, int userID, string userName, bool isAwesome)
        {
            DataRow row = table.NewRow();
            row["userID"] = userID;
            row["userName"] = userName;
            row["isAwesome"] = isAwesome;
            return row;
        }

        static void printTable(DataTable table)
        {
            foreach (DataRow row in table.Rows)
            {
                foreach (object val in row.ItemArray)
                {
                    Console.Write("{0}, ", val);
                }
                Console.WriteLine();
            }
        }


        static void Main(string[] args)
        {
            DataTable table = getDataTable();
            table.Rows.Add(getRow(table, 1, "Juliet", true));
            table.Rows.Add(getRow(table, 2, "Sean Hannity", false));
            table.Rows.Add(getRow(table, 3, "Charles Darwin", true));

            Console.WriteLine("Before:");
            printTable(table);

            // adding a row at index 1, between me and Sean Hannity
            Console.WriteLine("------------\nAfter:");
            DataRow barackRow = getRow(table, 4, "Barack Obama", true);
            table.Rows.InsertAt(barackRow, 1);
            printTable(table);

            Console.Write("Press any key. . .");
            Console.ReadKey(true);
        }        
    }
}

【讨论】:

  • 嗨朱丽叶!请你可以做一个样品。没事的。谢谢
【解决方案2】:

示例:

            DataTable table = new DataTable();
            table.Columns.Add("a", typeof(int));

            DataRow r = table.NewRow();
            r[0] = 10;
            table.Rows.Add(r);

            r = table.NewRow();
            r[0] = 12;
            table.Rows.InsertAt(r, 0);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-05-24
    • 1970-01-01
    • 2018-10-22
    • 2018-06-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多