Display Row Numbers in a DataGrid

Put template columns to work.

Jeff Prosise

October 30, 2009

1 Min Read
ITPro Today logo

ask the PRO: Bonus Info

LANGUAGES: C#

TECHNOLOGIES: DataGrid

 

Display Row Numbers in a DataGrid

Put template columns to work.

 

By Jeff Prosise

 

In CustomizeDataGrid Behavior, I showed you how to create a DataGrid column thatdisplays images obtained from a database. Well, as long as we're on the subjectof template columns, let's put them to work one more time, displaying rownumbers in a DataGrid. Simply declare a template column containing adata-binding expression that renders and auto-increments a row-number variable(see Figure 1).

 

<%@ Import Namespace="System.Data.SqlClient" %>

 

  

    

               AutogenerateColumns="false" Width="100%"         Font-Name="Verdana" Font-Size="8pt">                                 ItemStyle-HorizontalAlign="center">                             <%# rownum++ %>                                                DataField="title" />                                             int rownum = 1;   void Page_Load (Object sender, EventArgs e) {    if (!IsPostBack) {        SqlConnectionconnection = new SqlConnection             ("server=localhost;database=pubs;uid=sa");           try {            connection.Open ();            SqlCommandcommand = new SqlCommand                 ("SELECT title FROM titles", connection);             SqlDataReaderreader = command.ExecuteReader ();            MyDataGrid.DataSource = reader;             MyDataGrid.DataBind ();        }        finally {            connection.Close ();        }    }} Figure 1. To include a column of row numbers in aDataGrid, use a template column that auto-increments a variable and outputs thevariable's value.   Here, rownum holds the row number, and a template columnrenders rownum into HTML and increments its value by one in each data-bindingoperation. It's simple, it's clean, and it works like a charm. There's no endto the magic you can work with template columns!   Jeff Prosise is the author of several books, including Programming Microsoft .NET(Microsoft Press). He's also a co-founder of Wintellect (http://www.wintellect.com), asoftware-consulting and education firm that specializes in .NET. Have aquestion for this column? Submit queries to [email protected].      

Sign up for the ITPro Today newsletter
Stay on top of the IT universe with commentary, news analysis, how-to's, and tips delivered to your inbox daily.

You May Also Like