DataTable class of .Net provides a good option to add Auto Number Column which we generally use for showing the Serial No. in the GridView, so we instead of getting that from DB we can use the DataTable .
You can add this type of column by setting some properties of that column.
For example:
DataTable dtItems = new DataTable();
//Add Auto No. Column to the DataTable
dtItems.Columns.Add(“SrNo”, typeof(int));
dtItems.Columns[“SrNo”].AutoIncrement = true;
dtItems.Columns[“SrNo”].AutoIncrementSeed = 1;
dtItems.Columns[“SrNo”].AutoIncrementStep = 1;
//Add three more columns to the DataTable
dtItems.Columns.Add(“ItemName”, typeof(string));
dtItems.Columns.Add(“Price”, typeof(int));
dtItems.Columns.Add(“Quantity”, typeof(int));
|
In the above lines of code, dtItems is my DataTable and I am adding a new Auto Number Column (SrNo).
And while you add a new Row in the DataTable, at that time, do not just assign any value to this column, it will be automatically incremented.
Code while adding new row :-
DataRow drItem = dtItems.NewRow();
drItem[“ItemName”] = “Item1”;
drItem[“Price”] = 100;
drItem[“Quantity”] = 1;
dtItems.Rows.Add(drItem);
|