GridView Serial Number using RowIndex

This article is written by Pon Saravanan  on 22-Sep-09 Last modified on :22-Sep-09

Display Serial Number in GridView using RowIndex

Some times we need to display a Serial Number in a GridView  to identify each row. We can use RowIndex property of the GridView row to show serial number column.

There are few ways to do this. The method i explained in source code will work with any datasource. Thats why i purposely used a collection based datasource. If you are using DataTable you can do like this
<asp:Label ID="lblNo" runat="server" Text="<%# Container.DataItemIndex + 1 %>" />

Source Code

MarkUp (*.ASPX)

<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "">
<html xmlns="">
<head runat="server">
    <title>Untitled Page</title>
    <form id="form1" runat="server">
        <asp:Button ID="Button1" runat="server" Style="width: 56px" Text="Button" />
        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
                        <asp:Label runat="server" ID="lblNo"></asp:Label>
                <asp:BoundField DataField="Name" />


Partial Class _Default
    Inherits System.Web.UI.Page

    Protected Sub Button1_Click(ByVal sender As Object, _
                                ByVal e As System.EventArgs) Handles Button1.Click
        GridView1.DataSource = System.Drawing.FontFamily.Families
    End Sub
    Protected Sub GridView1_RowDataBound(ByVal sender As Object, _
                ByVal e As GridViewRowEventArgs) Handles GridView1.RowDataBound
        If (e.Row.RowType = DataControlRowType.DataRow) Then
            Dim lblNo As Label
            lblNo = DirectCast(e.Row.FindControl("lblNo"), Label)
            lblNo.Text = e.Row.RowIndex + 1
        End If
    End Sub
End Class

    send 2/16/2011 9:58:21 PM

Captcha Image
For you specially:  
Captcha Text Enter the text in the image.(Not Case sensitive)    

Spam Bot Trap


Select Theme