How do I add an ordinal column to the DataTable, incrementing the number from 1, and in the first column?
<summary>
Add an ordinal column to the DataTable, incrementing the number from 1
</summary>
<param >DataTable</param>
<returns></returns>
Private DataTable addserinumtodatatable (DataTable DT)
{
Value that needs to be returned
DataTable dtnew;
if (dt. Columns.indexof ("serial number") >= 0)
{
dtnew = DT;
}
else//Add an ordinal column, and in the first column
{
int rowlength = dt. Rows.Count;
int collength= dt. Columns.count;
datarow[] newrows = new Datarow[rowlength];
Dtnew = new DataTable ();
Add the ordinal column in the first column
DTNEW.COLUMNS.ADD ("serial number");
for (int i = 0; i < collength; i++)
{
DTNEW.COLUMNS.ADD (dt. Columns[i]. ColumnName);
Copy data from DT
for (int j = 0; J < Rowlength; J + +)
{
if (newrows[j] = = null)
NEWROWS[J] = Dtnew.newrow ();
After populating the second column with additional data, because the first column is the new ordinal columns
NEWROWS[J][I+1] = dt. Rows[j][i];
}
}
foreach (DataRow row in newrows)
{
DTNEW.ROWS.ADD (row);
}
}
Fills an ordinal column, incrementing from 1
for (int i = 0; i < dt. Rows.Count; i++)
{
dtnew.rows[i]["serial number"] = i + 1;
}
return dtnew;
}
Private DataTable DT;
private void Form1_Load (object sender, EventArgs e)
{
DT = new DataTable ();
Dt. Columns.Add ("name");
Dt. Columns.Add ("Price");
Dt. Rows.Add ("cabbage", 12);
Dt. Rows.Add ("cabbage", 12);
Dt. Rows.Add ("cabbage", 12);
Dt. Rows.Add ("cabbage", 12);
Dt. Rows.Add ("cabbage", 12);
DataTable DT2 = addserinumtodatatable (DT);
Datagridview1.datasource = DT2;
}
Add an ordinal column to a DataTable