Sunday, September 26, 2010

Displaying RowNumber in datagrid control

In this post I will show you how you can display row number in datagrid control using IMultiValueConverter.Let us start with the code.The code shown in the List 1 is used to bind using the IMultiValueConverter and the passing parameter for the binding converter are the binding and parent datagrid control

< DataGridTextColumn Header="Row Number" IsReadOnly="True"> < DataGridTextColumn.Binding> < MultiBinding Converter="{StaticResource rowNumberConverter}"> < Binding /> < Binding RelativeSource="{RelativeSource FindAncestor, AncestorType={x:Type DataGrid}}" /> < /MultiBinding> < /DataGridTextColumn.Binding> < /DataGridTextColumn>
List 1
Now in the converter I have simple code to show the row number of the current element which is passed to the converter in first parameter. I have store it in the object type variable. As I don't know what is the type of the first parameter and then I created another parameter of type data grid control and save the second parameter in it. Now in the next statement I have get the Index of the passed parameter in the data grid control and also added 1 in it, as IndexOf will return 0 for the first element. You can see the code in List 2.

public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture)  {   Object item = values[0];  DataGrid grdPassedGrid = values[1] as DataGrid; int intRowNumber = grdPassedGrid.Items.IndexOf(item) + 1; return intRowNumber.ToString().PadLeft(2, '0');  }
List 2

And you can see the Row Number column in the Image 1, I have set the header text of the column to "Row Number", You can changed it to you requirements.
Image 1

In the Image 1 you can see that I have used the left padding for the row number, as you can see that each row number is padded left by 0 I have used it to 2 values, You can also pass the length of your padding in the parameter of the IMultiValueConverter. You can download the source code from here.

All and any comments / bugs / suggestions are welcomed!


David said...

A nice extension is to display the row number in the row header instead of an extra column:

<DataGrid ...>
    <Style TargetType="DataGridRowHeader">
        <Setter Property="Content">
                <MultiBinding ...>

Nazbullah Ansari said...

First time using wpf framework ..can you guide me where I will add the convert code .

Nazbullah Ansari said...
This comment has been removed by the author.