How to Add Auto Number Column in Asp.net GridView

Description:- 
While working in ASP.NET, you often come across a need to display serial number or Auto-number in a Grid view control. This can be accomplished by adding the Container.DataItemIndex in the html mark-up of the Gridview control. On GridView Control add new Template Field and bind Container.DataItemIndex.

<div>
   <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
      <HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
      <AlternatingRowStyle BackColor="#BFE4FF" />
      <Columns>
         <asp:TemplateField HeaderText="No.">
            <ItemTemplate><%# Container.DataItemIndex + 1 %></ItemTemplate>
         </asp:TemplateField>
         <asp:BoundField DataField="CountryId" HeaderText="CountryId" />
         <asp:BoundField DataField="CountryName" HeaderText="CountryName"/>
      </Columns>
   </asp:GridView>
</div>

On my Code behind I have Bind Country Table in GridView for taking Data from SQL Server.

Protected void Page_Load(object sender, EventArgs e)
{
   SqlDataAdapter adapter = new SqlDataAdapter();
   DataSet ds = new DataSet();
   int i = 0;
   string sql = null;
   string connetionString = "Data Source=’ServerName’;Initial Catalog=’ DataSourceName’;Persist        Security Info=True;User ID=’UserName’;Password=’Password’";
  sql = "select * from Country";
  SqlConnection connection = new SqlConnection(connetionString);
  connection.Open();
  SqlCommand command = new SqlCommand(sql, connection);
  adapter.SelectCommand = command;
  adapter.Fill(ds);
  adapter.Dispose();
  command.Dispose();
  connection.Close();
  GridView1.DataSource = ds.Tables[0];
  GridView1.DataBind();
}

Now check on your browser for Index.

Related Posts

Previous
Next Post »

Thanks for comments.....