Ian Kelling
Ian Kelling

Reputation: 10021

WPF Datagrid row number

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="...."         />

Upvotes: 8

Views: 9361

Answers (1)

sparks
sparks

Reputation: 41

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.

Upvotes: 4

Related Questions