Wednesday, November 9, 2011

Displaying ASP GridView row index number

You can achieve this through two way:
Method 1
Step 1. Add this your GridView:

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="id"
DataSourceID="SqlDataSource1" OnRowCreated="GridView1_RowCreated" >

<Columns>
<asp:TemplateField HeaderText="RowId">
<ItemTemplate><asp:Label runat="server" />                      
</ItemTemplate>            
</asp:TemplateField> 
...
</Columns>


Step 2: Add following GridView Event code snippet to your code – behind file (.cs)


protected void GridView1_RowCreated(object sender, 
System.Web.UI.WebControls.GridViewRowEventArgs e)
{ 
if (e.Row.RowType == DataControlRowType.DataRow) {
// Retrieve the Label from the first column.
Label myLabel = (Label)e.Row.Cells[0].Controls[0]; 

// Set Label text equal to the rowIndex +1
myLabel.Text = e.Row.RowIndex.ToString() + 1; 
}
}


Method 2
The another way to do it is this one in the Columns section of your GridView control:

<asp:GridView ID="GridView1" runat="server" AllowPaging="True" AllowSorting="True"
AutoGenerateColumns="False" DataSourceID="SqlDataSource1" PageSize="5">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<%# Container.DataItemIndex + 1 %>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="CategoryName" HeaderText="CategoryName" SortExpression="CategoryName" />
<asp:BoundField DataField="Description" HeaderText="Description" SortExpression="Description" />
</Columns>
</asp:GridView>

No comments :

Post a Comment