How to Add a Counter Column to the DataGrid?


ASP.NET DataGrid web control is one of the simplest way to display the data. This article explains how to add functionality to add a counter column to the DataGrid. In short the article is about displaying the count for each row in the DataGrid .

The solution is as follows.Create a webform with a DataGrid control : 

<asp:Datagrid id= "Datagrid1" style="Z-INDEX: 101; LEFT: 6px; POSITION: absolute; TOP: 14px" runat="server"><Columns>
<asp:TemplateColumn>
<ItemTemplate>
<asp:Label id="Label1" Runat ="server" > <%#getCount%> </asp:Label>
</
ItemTemplate>
</asp:TemplateColumn>
</
Columns>
</asp:DataGrid>

In the code behind write the code: 

Dim count As Integer
Function
getcount() As Integer
count = count + 1
Return count
End Function
Private
Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'Put user code to initialize the page here
Dim strConn As String = "server=localhost;uid=sa;password=;database=northwind"
Dim myConn As New SqlConnection(strConn)
Dim strSQLData As String = "SELECT Orderid FROM Orders"
Dim myCmd As New SqlCommand(strSQLData, myConn)
Dim myRdr As SqlDataReader
myConn.Open()
myRdr = myCmd.ExecuteReader()
DataGrid1.DataSource = myRdr
DataGrid1.DataBind()
myRdr.Close()
myConn.Close()
End Sub


Similar Articles