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" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Button ID="Button1" runat="server" Style="width: 56px" Text="Button" />
        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
            <Columns>
                <asp:TemplateField>
                    <ItemTemplate>
                        <asp:Label runat="server" ID="lblNo"></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:BoundField DataField="Name" />
            </Columns>
        </asp:GridView>
    </div>
    </form>
</body>
</html>

Code-Behind(*.VB)

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
        GridView1.DataBind()
    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











Comments
  • GUEST
    send 2/16/2011 9:58:21 PM


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



Spam Bot Trap



   



Select Theme
White
Blue
Brown
Gray