In
this article I am going to explain how to auto generate and display Serial
number (row number) in asp.net gridview data control using C# and vb.net.
In
the previous article I have explained how to check uncheck OR select/deselectcheckboxes in asp.net gridview control using Jquery, how to Check and uncheckall records or showing rows using checkbox control in Gridview asp.net usingJavascript and how to fill dropdownlist with months name using System.Globalizationin asp.net .
Description:
The
serial number can be generated using DataItemIndex in gridview. Add Templatefield
and put the below given in ItemTemplate :
<%# Container.DataItemIndex + 1 %>
Implementation:
HTML Markup:
<fieldset style="width:30%">
<legend> Auto generate and display Serial
number in Gridview</legend>
<asp:GridView ID="GridView1" runat="server"
AllowPaging="True" AutoGenerateColumns="False" DataKeyNames="id">
<Columns>
<asp:TemplateField HeaderText="S.No.">
<ItemTemplate>
<%#
Container.DataItemIndex + 1 %>
</ItemTemplate>
<ItemStyle HorizontalAlign="Center" />
</asp:TemplateField>
<asp:BoundField DataField
= "Name"
HeaderText = "Movie Name" >
<HeaderStyle HorizontalAlign="Center" />
<ItemStyle HorizontalAlign="Center" />
</asp:BoundField>
<asp:BoundField DataField
= "Genre"
HeaderText = "Genre" >
<HeaderStyle HorizontalAlign="Center" />
<ItemStyle HorizontalAlign="Center" />
</asp:BoundField>
<asp:BoundField DataField
= "Budget"
HeaderText = "Budget">
<HeaderStyle HorizontalAlign="Center" />
<ItemStyle HorizontalAlign="Center" />
</asp:BoundField>
</Columns>
</asp:GridView>
</fieldset>
Import the
namespace:
C#
code:
using
System.Data;
using
System.Data.SqlClient;
using
System.Configuration;
VB.net
Code:
Imports
System.Data
Imports
System.Data.SqlClient
Imports
System.Configuration
Bind the
Gridview
Create
a method to bind Gridview and call it on page load.
C#
code:
SqlConnection
con = new SqlConnection(ConfigurationManager.ConnectionStrings["connection"].ToString());
protected void Page_Load(object
sender, EventArgs e)
{
if
(!IsPostBack)
{
BindGrid();
}
}
public void BindGrid()
{
try
{
SqlCommand
cmd = new SqlCommand("select * from Tb_Movie", con);
con.Open();
SqlDataAdapter
adp = new SqlDataAdapter(cmd);
DataTable
dt = new DataTable();
adp.Fill(dt);
if
(dt.Rows.Count > 0)
{
grdmovie.DataSource = dt;
grdmovie.DataBind();
}
}
catch (Exception ex)
{
}
}
VB.net
Code:
Private
con As New SqlConnection(ConfigurationManager.ConnectionStrings("connection").ToString())
Protected Sub Page_Load(sender As
Object, e As EventArgs) Handles
Me.Load
If Not IsPostBack Then
BindGrid()
End If
End Sub
Public Sub BindGrid()
Try
Dim
cmd As New SqlCommand("select
* from Tb_Movie", con)
con.Open()
Dim
adp As New SqlDataAdapter(cmd)
Dim
dt As New DataTable()
adp.Fill(dt)
If
dt.Rows.Count > 0 Then
grdmovie.DataSource = dt
grdmovie.DataBind()
End
If
Catch
ex As Exception
End Try
End Sub
No comments:
Post a Comment