Display Row Numbers in a DataGrid

Put template columns to work.

ask the PRO: Bonus Info

LANGUAGES: C#

TECHNOLOGIES: DataGrid

 

Display Row Numbers in a DataGrid

Put template columns to work.

 

By Jeff Prosise

 

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

 

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

 

<html>

  <body>

    <form runat="server">

      <asp:DataGrid ID="MyDataGrid" RunAt="server"

        AutogenerateColumns="false" Width="100%"

        Font-Name="Verdana" Font-Size="8pt">

        <Columns>

          <asp:TemplateColumn HeaderText="Number"

            ItemStyle-HorizontalAlign="center">

            <ItemTemplate>

               <%# rownum++ %>

            </ItemTemplate>

          </asp:TemplateColumn>

          <asp:BoundColumn HeaderText="Title"

            DataField="title" />

        </Columns>

        <HeaderStyle HorizontalAlign="center" />

        <AlternatingItemStyle BackColor="beige" />

      </asp:DataGrid>

    </form>

  </body>

</html>

 

<script language="C#" runat="server">

int rownum = 1;

 

void Page_Load (Object sender, EventArgs e)

{

    if (!IsPostBack) {

        SqlConnection connection = new SqlConnection

             ("server=localhost;database=pubs;uid=sa");

 

        try {

            connection.Open ();

            SqlCommand command = new SqlCommand

                 ("SELECT title FROM titles", connection);

            SqlDataReader reader = command.ExecuteReader ();

            MyDataGrid.DataSource = reader;

            MyDataGrid.DataBind ();

        }

        finally {

            connection.Close ();

        }

    }

}

</script>

Figure 1. To include a column of row numbers in a DataGrid, use a template column that auto-increments a variable and outputs the variable's value.

 

Here, rownum holds the row number, and a template column renders rownum into HTML and increments its value by one in each data-binding operation. It's simple, it's clean, and it works like a charm. There's no end to 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), a software-consulting and education firm that specializes in .NET. Have a question for this column? Submit queries to [email protected].

 

 

 

Hide comments

Comments

  • Allowed HTML tags: <em> <strong> <blockquote> <br> <p>

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
Publish