Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF Datagrid row number

Tags:

wpf

datagrid

I have a datagrid. I would like a column that displays simply 1 2 3 4 ... in the rows, up to as many rows as I have being created from my other data bindings.

 <dg:DataGridTextColumn Header="#" IsReadOnly="True"
                                           Binding="...."         />
like image 739
Ian Kelling Avatar asked Aug 26 '09 04:08

Ian Kelling


1 Answers

I've spent a good chunk of time today looking through MSDN documentation and other threads for this answer. The way I've settled on implementing this is binding a property (that I created) specifically for line numbers in the objects in the collection that the datagrid is bound to. e.g.

public class myItem
{
    public int LineNumber { get; set; }
    // rest of your object...
}

You'll have to manually set the line number in the objects yourself.

Another way of adding line numbers can be found here. Here's the code:

datagrid.LoadingRow += 
    new EventHandler<DataGridRowEventArgs>(datagrid_LoadingRow);

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

This implementation puts the line numbers in the row headers and does not require you to put a property just for line numbers in your objects. However, if you need to insert or delete a row from the datagrid, the line numbers will not update.

like image 94
sparks Avatar answered Sep 28 '22 01:09

sparks