如何在datatable中添加一序号列,编号从1依次递增,并且在第一列?
/// <summary>
/// 在DataTable中添加一序号列,编号从1依次递增
/// </summary>
/// <param >DataTable</param>
/// <returns></returns>
private DataTable AddSeriNumToDataTable(DataTable dt)
{
//需要返回的值
DataTable dtNew;
if (dt.Columns.IndexOf("序号") >= 0)
{
dtNew = dt;
}
else //添加一序号列,并且在第一列
{
int rowLength = dt.Rows.Count;
int colLength= dt.Columns.Count;
DataRow[] newRows = new DataRow[rowLength];
dtNew = new DataTable();
//在第一列添加“序号”列
dtNew.Columns.Add("序号");
for (int i = 0; i < colLength; i++)
{
dtNew.Columns.Add(dt.Columns[i].ColumnName);
//复制dt中的数据
for (int j = 0; j < rowLength; j++)
{
if (newRows[j] == null)
newRows[j] = dtNew.NewRow();
//将其他数据填充到第二列之后,因为第一列为新增的序号列
newRows[j][i+1] = dt.Rows[j][i];
}
}
foreach (DataRow row in newRows)
{
dtNew.Rows.Add(row);
}
}
//对序号列填充,从1递增
for (int i = 0; i < dt.Rows.Count; i++)
{
dtNew.Rows[i]["序号"] = i + 1;
}
return dtNew;
}
private DataTable dt;
private void Form1_Load(object sender, EventArgs e)
{
dt = new DataTable();
dt.Columns.Add("名称");
dt.Columns.Add("价格");
dt.Rows.Add("白菜", 12);
dt.Rows.Add("白菜", 12);
dt.Rows.Add("白菜", 12);
dt.Rows.Add("白菜", 12);
dt.Rows.Add("白菜", 12);
DataTable dt2 = AddSeriNumToDataTable(dt);
dataGridView1.DataSource = dt2;
}