Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple way to display row numbers on WPF DataGrid

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.

like image 758
JohnB Avatar asked Jan 11 '11 20:01

JohnB


3 Answers

One way is to add them in the LoadingRow event for the DataGrid

<DataGrid Name="DataGrid" LoadingRow="DataGrid_LoadingRow" ...

void DataGrid_LoadingRow(object sender, DataGridRowEventArgs e)
{
    e.Row.Header = (e.Row.GetIndex()).ToString(); 
}

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

<DataGrid ItemsSource="{Binding ...}"
          behaviors:DataGridBehavior.DisplayRowNumber="True"> 
like image 120
Fredrik Hedblad Avatar answered Nov 11 '22 17:11

Fredrik Hedblad


Adding a short info about Fredrik Hedblad answer.

<DataGrid Name="DataGrid" LoadingRow="DataGrid_LoadingRow" ...

void DataGrid_LoadingRow(object sender, DataGridRowEventArgs e)
{
    e.Row.Header = (e.Row.GetIndex()+1).ToString(); 
}

...If you want to start numbering from 1

like image 45
JohnnyJaxs Avatar answered Nov 11 '22 18:11

JohnnyJaxs


If 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:

<DataGrid ItemsSource="{Binding MyObservableCollection}" AlternationCount="{Binding MyObservableCollection.Count}" />

Or:

<DataGrid ItemsSource="{Binding MyObservableCollection}" AlternationCount="{Binding Items.Count, RelativeSource={RelativeSource Self}" />

Either should work.

Then, assuming you're using a DataGridTextColumn for your leftmost column you do the following in your DataGrid.Columns definition:

<DataGrid.Columns>
   <DataGridTextColumn Binding="{Binding AlternationIndex, RelativeSource={RelativeSource AncestorType=DataGridRow}}"
</DataGrid.Columns>

If you don't want to start at 0, you can add a converter to your binding to increment the index.

like image 11
GrantA Avatar answered Nov 11 '22 16:11

GrantA