C# 在行之间添加数据行?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1038756/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 06:43:22 来源:igfitidea点击:
Adding Datarow between Rows?
提问by subprime
how can i add rows between existing rows in a datatable ? Thanks
如何在数据表中的现有行之间添加行?谢谢
采纳答案by Juliet
dataTable.Rows.InsertAt(DataRow row, int position);
dataTable.Rows.InsertAt(DataRow row, int position);
Sample:
样本:
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);
}
}
}
回答by Ahmed Said
Sample:
样本:
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);