这种方式也可以,但是不太完美
DataRow dr = dt_hr.NewRow();
for (int m = 0; m < dt_hr.Columns.Count; m++)
{
dr[m] = dt_hr.Rows[j][m];
}
dr[15] = promote_time;
dt_hr.Rows[j].Delete();
dt_hr.Rows.InsertAt(dr,loop_end_free+1);
dt_hr.AcceptChanges();
static void Main(string[] args)
{
DataTable dt = InitData();
Console.WriteLine("初始数据:");
for (int i = 0; i < dt.Rows.Count; i++)
{
Console.WriteLine(dt.Rows[i][0] + " " + dt.Rows[i][1]);
}
dt = Up(dt, 3);
Console.WriteLine("移动第3行后:");
for (int i = 0; i < dt.Rows.Count; i++)
{
Console.WriteLine(dt.Rows[i][0] + " " + dt.Rows[i][1]);
}
Console.ReadLine();
}
static DataTable InitData()
{
DataTable dt = new DataTable();
dt.Columns.Add("id", typeof(string));
dt.Columns.Add("name", typeof(string));
DataRow r;
string[] rowArray = new string[2];
for (int i = 0; i < 5; i++)
{
rowArray[0] = i.ToString();
rowArray[1] = "item" + i;
r = dt.NewRow();
r.ItemArray = rowArray;
dt.Rows.Add(r);
}
return dt;
}
/// <summary>
/// 向上移动,也就是和自己上面那行数据交换,想下仿造这样写
/// </summary>
/// <param name="dt"></param>
/// <param name="index"></param>
/// <returns></returns>
static DataTable Up(DataTable dt, int index)
{
int cindex = (index - 1) < 0 ? 0 : index - 1;
object[] data = dt.Rows[index].ItemArray;
object[] cdata = dt.Rows[cindex].ItemArray;
dt.Rows[cindex].ItemArray = data;
dt.Rows[index].ItemArray = cdata;
return dt;
}