Sometimes you might need to display a column of serial number for GridView rows and you want it to be auto increment as number of rows increases. This can be very easily achieved by different ways. You can do it in the ItemTemplate of GridView control or you can do in code behind file. Although it is not difficult in code behind file but it is very easy to be achieved in ItemTemplate with a single line of code.
1.Create a new Empty Web Site in Visual Studio 2010 either in Visual Basic or Visual C#.
2.Add a Web Form in the Web Site. No Need to change name of the Page
3.Add a GridView control in Web Form and write code below in GridView.
See in ItemTemplate, I have add a single line of code to auto generate serial number.
<asp:GridView ID="GridView1" AutoGenerateColumns="false" runat="server">
<Columns>
<asp:TemplateField HeaderText="Serial No">
<ItemTemplate>
<%# Container.DataItemIndex + 1%>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField HeaderText="CustomerID" DataField="CustomerID" />
<asp:BoundField HeaderText="CompanyName" DataField="CompanyName" />
<asp:BoundField HeaderText="ContactName" DataField="ContactName" />
<asp:BoundField HeaderText="City" DataField="City" />
<asp:BoundField HeaderText="Country" DataField="Country" />
</Columns>
</asp:GridView>
4.Namespaces used in the code
Visual Basic
Imports System.Data
Imports System.Data.SqlClient
Visual C#
using System.Data;
using System.Data.SqlClient;
5.Write code below in code behind file
CustomersData() functions is written to get data from Customers table of NORTHWIND database in a DataSet object. In Page Load event, GridView is bound to CustomersData() function.
Visual Basic
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
GridView1.DataSource = CustomersData()
GridView1.DataBind()
End Sub
Public Function CustomersData() As DataSet
Dim text As String = "SELECT * FROM Customers"
Dim connString As String = "Data Source=YourServer;Initial Catalog=NORTHWND;Integrated Security=True"
Dim conn As New SqlConnection(connString)
Dim cmd As New SqlCommand(text, conn)
conn.Open()
Dim da As New SqlDataAdapter(cmd)
Dim ds As New DataSet()
da.Fill(ds)
conn.Close()
Return ds
End Function
Visual C#
protected void Page_Load(object sender, EventArgs e)
{
GridView1.DataSource = CustomersData();
GridView1.DataBind();
}
public DataSet CustomersData()
{
string text = "SELECT * FROM Customers";
string connString = "Data Source=YourServer;Initial Catalog=NORTHWND;Integrated Security=True";
SqlConnection conn = new SqlConnection(connString);
SqlCommand cmd = new SqlCommand(text, conn);
conn.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
conn.Close();
return ds;
}
6.Now you can see website in your browser