In ADO.NET, I’m using a DataAdapter.Fill (..)
call to fill a DataTable with values from a database. Then I bind the DataTable to a DataGrid to allow scrolling through all the values, editing, and updating changes back to the database. All standard stuff. I use the Visual Studio Windows Forms wizards for all of it since it is so standard.
But now I want to display a left-side column (not part of the database row) to number the rows that show up in the DataGrid. I would still like to keep the bound row data as is, with auto-updating back to the database and so on. Obviously, I can’t do this with wizards.
METHOD 1
If I was doing it manually, I would change the DataTable load query to include a dummy integer column to inject the desired row number column into the returned table:
SELECT ‘’ as Num, * from MyTable
Then I would programmatically insert row numbers into that field before binding the DataTable to the grid, which would show the row numbers as desired. I would hope that the automatic updating code for the DataTable would just ignore the extra column in the grid.
METHOD 2
Another possible way is to programmatically add a new column to the DataGrid after it is bound to the DataSource (my DataTable). Then I would populate the new column with row numbers before the grid was displayed.
QUESTION
But before I abandon the convenient wizards and do the manual work for everything, I wanted to ask if there is a standard way of doing this sort of thing. I cannot believe I’m the first person to want to use row numbers (not part of the database row) in a grid display.
I have searched here and on various other forums for ideas, but none of them talk about what happens to the updating code when you inject new columns into the table loading query (method 1) or into the grid after you bind the DataGrid to the Datasource (method 2).
I even thought of using two adjacent grid controls fed from two different binding sources. But the code required to keeping them synchronized during scrolls seems like even more work.
Could anyone point me to the best way to solve this problem or provide a code snippet? I’m OK with going into the form designer-generated code to add a column to the bound DataGrid, but I get lost in trying to find and understand the updating part that updates changes back into the database. Thank you.