articles

GridView Control in ASP.Net

Pushpendra Singh14406 30-Oct-2010

The GridView control enables you to connect to a data source and display data in tabular format.

<asp:GridView ID="GridView1" runat="server">
</asp:GridView>

GridView Control in ASP.Net

The GridView control supports the following features:

·         Binding   to data source controls.

·         Built -in sorting capabilities.

·         Built-in updating and deleting capabilities.

·         Build-in paging capabilities.

·         Built-in row selection capabilities.

·         New column types such as CheckBoxField and Image Field.

·         Multiple data fields for the hyperlink columns.

·         Multiple data key fields for selection, updates, and deletes.

·         Customizable appearance through themes and styles.

Code:

<asp:GridView ID="GridView1"runat="server" AllowPaging="True"
AutoGenerateColumns="False"OnRowEditing="GridView1_RowEditing" OnRowCancelingEdit="GridView1_RowCancelingEdit" OnRowUpdating="GridView1_RowUpdating" OnRowCommand="GridView1_RowCommand" OnRowDeleting="GridView1_RowDeleting"
ShowFooter="True" CellPadding="4" ForeColor="#333333" GridLines="None">
  <RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
<Columns>
 <asp:TemplateField HeaderText="ID">
 <ItemTemplate>
 <asp:Label ID="lblid" runat="server" Text='<%# Eval("id")%>'>   </asp:Label>
 </ItemTemplate>
 <EditItemTemplate>
 <asp:Label ID="lblid1" runat="server" Text='<%# Eval("id")%>'> </asp:Label>
 </EditItemTemplate>
 <FooterTemplate>
 <asp:TextBox ID="txtid2" runat="server"></asp:TextBox></FooterTemplate>
 </asp:TemplateField>
           
<asp:TemplateField HeaderText="PASS">
<ItemTemplate>
<asp:Label ID="lblid2" runat="server" Text='<%# Eval("pass")%>'> </asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtid3"runat="server"Text='<%#Eval("pass")%>'></asp:TextBox> </EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtid4" runat="server"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
 
<asp:TemplateField HeaderText="ID">
<ItemTemplate>
<asp:Label ID="lblid3" runat="server" Text='<%# Eval("name")%>'> </asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtid5"runat="server"Text='<%#Eval("name")%>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtid6" runat="server"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
 
<asp:TemplateField HeaderText="Edit">
<ItemTemplate>
<asp:LinkButton ID="lnkbtn1"runat="server"
CommandName="edit">edit</asp:LinkButton>
<asp:LinkButton ID="LinkButton1" runat="server" CommandName="delete">delete</asp:LinkButton>
</ItemTemplate>
<EditItemTemplate>
<asp:LinkButton ID="lnkbtn2" runat="server" CommandName="edit">edit</asp:LinkButton>
<asp:LinkButton ID="lnkbtn3" runat="server" CommandName="update">update</asp:LinkButton>
<asp:LinkButton ID="lnkbtn4" runat="server" CommandName="cancel">cancel</asp:LinkButton>
</EditItemTemplate>
<FooterTemplate>
<asp:LinkButton ID="lnkbtn5" runat="server" CommandName="ADD">ADD</asp:LinkButton>
</FooterTemplate>
</asp:TemplateField>
</Columns>
       
</asp:GridView>

 

 

GridView Control in ASP.Net

Bind Data in GridView:

Data will bind when page loaded.

protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
BindData();// this function is called when the page is loaded.
}
}
 
 
public void BindData()
{
// Here data is fetched from the database through stored procedure(insert_reg).
 
GridView1.DataSource = Class1.execute_spfill_grid("insert_reg");
// Here data is bind to the control and show on page
 
GridView1.DataBind();
}


In above code execute_spfill_grid is a function made in Class1.cs which is described below.

And insert_reg is a stored procedure made in backend.This is described below

 

GridView Control in ASP.Net

GridView Event:

 

GridView Control in ASP.Net

 

RowEditing

Occurs when a row's Edit button is clicked, but before the GridView control enters edit mode.

RowCancelingEdit

Occurs when the Cancel button of a row in edit mode is clicked, but before the row exits edit mode.

RowCommand

Occurs when a button is clicked in a GridView control.

RowDeleting

Occurs when a row's Delete button is clicked, but before the GridView control deletes the row.

 

 

RowEditing event is used to enable editing in GridView

 

protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
    {
        GridView1.EditIndex = e.NewEditIndex;
        BindData();
    }

 

RowCancelingEdit event is used to cancel edit mode.

 

     protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {
        GridView1.EditIndex = -1;
        BindData();
    }

The zero-based index of the row to edit. EditIndex = -1, which indicates that no row is being edited.

GridView Control in ASP.Net

Update , Add and Delete data in gridview:

Row updating event is used for updating data

protected void GridView1_RowUpdating(object sender,GridViewUpdateEventArgs e)
{
// Here  FindControl will find the Id in which updating will be done.
string i = ((Label)GridView1.Rows[e.RowIndex].Cells[0].FindControl("lblid1")).Text;
string pas = ((TextBox)GridView1.Rows[e.RowIndex].Cells[1].FindControl("txtid3")).Text;
string nm = ((TextBox)GridView1.Rows[e.RowIndex].Cells[2].FindControl("txtid5")).Text;
Class1.update_reg_form("update_reg", i, pas, nm);
// update_regform is a function which fetch the data from database through stored procedure(update_reg).
GridView1.EditIndex=-1;
BindData();
}

 

The RowCommand event is raised whenever any button associated with a row in the GridView is clicked. This provides for programmatically determining which specific command button is clicked and take appropriate action.

Here this event is used for Inserting data

  
protected void GridView1_RowCommand(object sender,GridViewCommandEventArgs e)
{
if (e.CommandName=="ADD")
{
// Here  FindControl will find the Id in which adding will be done.
 
string i = ((TextBox)GridView1.FooterRow.FindControl("txtid2")).Text;
string pas = ((TextBox)GridView1.FooterRow.FindControl("txtid4")).Text;
string nm = ((TextBox)GridView1.FooterRow.FindControl("txtid6")).Text;
 
            Class1.ADD_reg_form("add_reg", i, pas, nm);
GridView1.EditIndex = -1;
BindData();
}
}

 

Row Deleting event is used to delete the data

protected void GridView1_RowDeleting(object sender,GridViewDeleteEventArgs e)
{  
string i = ((Label)GridView1.Rows[e.RowIndex].Cells[0].FindControl("lblid")).Text;
Class1.DEL_reg_form("del_reg", i);
GridView1.EditIndex = -1;
 BindData();
}


GridView Control in ASP.Net

 

Add both namespace in every .cs page in which you want to use data and SQL related keyword

using System.Data;
using System.Data.SqlClient;


Class1.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Data;
using System.Data.SqlClient;
using System.Web;
 
public class Class1
{
 
    // this function is used to bind data
    public static DataSet execute_spfill_grid(string spname)
    {
 
        SqlConnection con = Connection.CreateConnection();
 
        DataSet ds = new DataSet();
 
        SqlCommand cmd = new SqlCommand();
        cmd.CommandText = spname;
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.Connection = con;
        con.Open();
        SqlDataAdapter da = new SqlDataAdapter(spname,con);
        da.Fill(ds);
    
        return ds;
      
    }
 
 
    public static void update_reg_form(string spname, string id, string pass, string name) // this function is used to update data
    {
        SqlConnection con = Connection.CreateConnection();
       
        SqlCommand cmd = new SqlCommand();
        cmd.CommandText = spname;
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.Parameters.Add("@id", SqlDbType.VarChar).Value = id;
        cmd.Parameters.Add("@pass", SqlDbType.VarChar).Value = pass;
        cmd.Parameters.Add("@name", SqlDbType.VarChar).Value = name;
 
        cmd.Connection = con;
        con.Open();
       
        cmd.ExecuteNonQuery();
        con.Close();
    }
 
    public static void ADD_reg_form(string spname, string id, string pass, string name)// this function is used to Add data
    {
        SqlConnection con = Connection.CreateConnection();
 
        SqlCommand cmd = new SqlCommand();
        cmd.CommandText = spname;
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.Parameters.Add("@id", SqlDbType.VarChar).Value = id;
        cmd.Parameters.Add("@pass", SqlDbType.VarChar).Value = pass;
        cmd.Parameters.Add("@name", SqlDbType.VarChar).Value = name;
 
        cmd.Connection = con;
        con.Open();
 
        cmd.ExecuteNonQuery();
        con.Close();
    }
 
    public static void DEL_reg_form(string spname, string id)// this function is used to Delete data
    {
        SqlConnection con = Connection.CreateConnection();
 
        SqlCommand cmd = new SqlCommand();
        cmd.CommandText = spname;
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.Parameters.Add("@id", SqlDbType.VarChar).Value = id;
      
 
        cmd.Connection = con;
        con.Open();
 
        cmd.ExecuteNonQuery();
        con.Close();
    }
}
 


In class1.cs  Connection keyword is used

Connection is class in whichCreateConnection function is created.

Connection.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Configuration;
using System.Web;
using System.Data;
using System.Data.SqlClient;
 
public class Connection
{
 
    public static SqlConnection CreateConnection()
    {
        string connectionstring;
        connectionstring = ConfigurationManager.ConnectionStrings["mycon"].ConnectionString;
        SqlConnection sqlcon = new SqlConnection(connectionstring);
        return sqlcon;
    }
 
   
}

 

 

mycon is connection object created in web.config

web.config:

<connectionStrings>
            <add name="mycon"connectionString="Data Source=(local);Initial Catalog=my; User Id=sa; Password=mindstick"providerName="System.Data.SqlClient"/>
      </connectionStrings>

Write this connection string above <system.web>

Stored procedure: 

This procedure is used to select data

Create procedure insert_reg
 
as
begin
select * from regform
end


This procedure is used to Insert data

Create procedure add_reg
@id varchar(50),
@pass varchar(50),
@name varchar(50)
as
begin
insert into regform
(id,pass,name
)
values
(
@id,
@pass,
@name
)
End


This procedure is used to Delete data

create procedure del_reg
@id varchar(50)
as
begin
delete  from regform where id=@id
end


This procedure is used to Update data

create procedure [dbo].[update_reg]
@id varchar(50),
@pass varchar(50),
@name varchar(50)
as
begin
update regform set pass=@pass,name=@name where id=@id
end

Updated 04-Mar-2020

Leave Comment

Comments

Liked By