Add an ordinal column to a DataTable

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.