I just want to display row numbers in the left-most column of my DataGrid
. Is there some attribute to do this?
Keep in mind, this isn't a primary key for my table. I don't want these row numbers to move with their rows when a column is sorted. I basically want a running count. It doesn't even need to have a header.
Just another answer to provide almost copy&paste example (not to be encouraged) for new people or people in a rush, inspired by answers inside this post by @GrantA and @Johan Larsson ( + many other people who answered to the numerous posts on that subject)
You do not need to re-create your own Attached Property
Note the parenthesis () around (ItemsControl.AlternationIndex) as warned in Fredrik Hedblad answer in Check if Row as odd number
Adding a short info about Fredrik Hedblad answer.
...If you want to start numbering from 1
One way is to add them in the LoadingRow event for the DataGrid
When items are added or removed from the source list then the numbers can get out of sync for a while. For a fix to this, see the attached behavior here:
WPF 4 DataGrid: Getting the Row Number into the RowHeader
Useable like this
It's an old question, but I would like to share something. I had a similar problem, all I needed was a simple
RowHeader
numeration of rows and Fredrik Hedblad's answer was almost complete for my problem.While this is great:
my headers messed up when removing and adding items. If you have buttons responsible for that just add
dataGrid.Items.Refresh();
under the 'deleting' code as in my case:That solved desyncronized numeration for me, because refreshing items calls
DataGrig_LoadingRow
again.And just to add to the discussion on this... (I spent too much time finding this out!).
You'll need to set the EnableRowVirtualization to False on the datagrid to prevent errors in the row sequencing:
The
EnableRowVirtualization
property is set totrue
by default. When theEnableRowVirtualization
property is set to true, the DataGrid does not instantiate aDataGridRow
object for each data item in the bound data source. Instead, the DataGrid creates DataGridRow objects only when they are needed, and reuses them as much as it can. MSDN Reference hereIf your data grid has its ItemsSource bound to a collection, bind the AlternationCount property of your data grid to either the the count property of your collection, or to the Items.Count property of your DataGrid as follows:
Or:
Either should work.
Then, assuming you're using a DataGridTextColumn for your leftmost column you do the following in your DataGrid.Columns definition:
If you don't want to start at 0, you can add a converter to your binding to increment the index.