Numbering rows in the DataGrid

Feb 23, 2009 at 4:42 PM
I'm interested in displaying the index of a row in the row header. Any ideas?
Feb 23, 2009 at 6:52 PM
Hi CorpPeon,

You can do this with a Style on your RowHeader.

<Style x:Key="RowHeadersWithId" TargetType="{x:Type dg:DataGridRowHeader}">
                <Setter Property="Content" Value="{Binding Id}"/>

You can put this Style in your resources and then set DataGrid's RowHeaderStyle property to use it.

Feb 24, 2009 at 11:09 AM
Thanks but the objects that my rows bind to do not have an Id property.

I'm interested in the grid itself showing a number, starting from 1 for the first row, and incrementing for each subsequent row. I would like the number to be unaffected by the sort order of the columns, so that the first visual row in the grid is always labelled 1 and so forth...
Apr 9, 2009 at 3:25 PM

You can attach the following handler to the LoadingRow event:

private void TheGrid_LoadingRow(object sender, DataGridRowEventArgs e)

e.Row.Header = ((sender as DataGrid).ItemContainerGenerator.IndexFromContainer(e.Row) + 1).ToString();

Apr 21, 2009 at 4:00 PM
Monsignor this is a cool way to do it - but I need a way to do this same thing in a grid where I occasionally add items to the underlying collection and have the numbers update automatically. (For example row 3 could become row 4, etc).

Does anyone have a good solution for that?