简体   繁体   中英

Insert row number as a column in datatable/dataset

My datatable/dataset doesn't contain a row number column. How can i via code enter a column as "Row No" that could tell me the row number entered.

Say Currently my dataset is

Col1 | Col2 | Col3
ABC    TIGER  USA 
DEF    LION   UK 
GHI    HORSE  UAE

Hence i wish to have as

Row No
1
2
3

how can i do that?

in case of datatable/dataset i think you don't need row no bc every row in datatable holds the index you can get it by index no. in case you are about the use that column in binding anywhere then while getting table from database you can add row no. eg

SELECT ROW_NUMBER() 
        OVER (ORDER BY EmployeeName) AS Row, 
    EmployeeId, EmployeeName, Salary 
FROM Employees

and if you want to add rowno in code behind that just loop thru you tables rows and add new column and set the values of index+1

Logically speaking, you can add the column to the select statement, or you can add the column in the app. If I couldn't add the row number in the select (not automatic in all DBs), I might add the column in the select:

Select 0 row_no, col1, col2, col2 from mytable

and populate the row_no column in the app:

int i = 0; foreach (DataRow r in dt.Rows) r["row_no"] = i++;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM