How to Perform Insert,Edit,Update,Delete,Cancel and Print operations in Gridview using C#

By
Gridview control has default layout to display the data in row and column. On browser side by default Gridview is converted in 'HTML' Tag. Gridview control have predefined event to add ,delete,Edit,sort,cancel the record. 
In this tutorial i will implement Insert,Edit,Update,cancel and Print operation in Gridview control.In our previous tutorial i have Explained How to perform Insert,Edit,Update and Print operation in Repeater control.
There are some steps to implement these whole concepts which are given below:-
Step 1 :- First open your visual studio-->File-->New-->website-->ASP.NET Empty Website -->OK-->Open solution Explorer-->Add New Web Form (Default.aspx).
Step 2 :- Now Add an Database.mdf file in your website -->Make a student table as shown below:-

create-table
Note:-You can create table separately in database(Sql ,MySQL etc.) and connect to this application .If you are facing any problem to add .mdf file on website then visit below :-
  1. How add .mdf file on asp.net website.
  2. How to solve sql server problems.
Step 3 :- Now open your Default.aspx page -->Click Source button from below-->Write the following Gridview layout code(html code) as given below:-

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="gridview.aspx.cs" Inherits="gridview" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
<title></title>
<style type="text/css">
.Gridview
{
font-family:Verdana;
font-size:10pt;
font-weight:normal;
color:black;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div>
    <asp:Label ID="Label1" runat="server" style="color: #800000" Text="*"></asp:Label>
    <br />
    <asp:LinkButton ID="LinkButton1" runat="server" onclick="LinkButton1_Click" 
        PostBackUrl="~/ptrint.aspx" style="font-weight: 700">Take Preview</asp:LinkButton>
<asp:GridView ID="GridView1" DataKeyNames="sid" runat="server"
AutoGenerateColumns="False" CssClass="Gridview" HeaderStyle-BackColor="#61A6F8"
ShowFooter="True" HeaderStyle-Font-Bold="true" HeaderStyle-ForeColor="White" 
onrowcommand="gvDetails_RowCommand" BackColor="White" BorderColor="#CC9966" 
BorderStyle="None" BorderWidth="1px" CellPadding="4" Width="889px"  AllowPaging="True" 
      Height="156px">
<Columns>
<asp:TemplateField HeaderText="Sid" HeaderStyle-HorizontalAlign="Left">
<ItemTemplate>
<EditItemTemplate>
<asp:Label ID="sid" runat="server" Text='<%#Eval("sid") %>'/>
</EditItemTemplate>
</ItemTemplate>
<FooterTemplate>
<asp:Label ID="Label2" runat="server" Text="Label"></asp:Label>
</FooterTemplate>
<HeaderStyle HorizontalAlign="Left"></HeaderStyle>
</asp:TemplateField>
<asp:TemplateField HeaderText="Name" HeaderStyle-HorizontalAlign="Left">
<ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="tname" runat="server" Text='<%#Eval("name") %>'/>
</EditItemTemplate>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
</FooterTemplate>
<HeaderStyle HorizontalAlign="Left"></HeaderStyle>
</asp:TemplateField>
<asp:TemplateField HeaderText="Age" HeaderStyle-HorizontalAlign="Left">
<ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="tage" runat="server" Text='<%#Eval("age") %>'/>
</EditItemTemplate>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>
</FooterTemplate>
<HeaderStyle HorizontalAlign="Left"></HeaderStyle>
</asp:TemplateField>
<asp:TemplateField HeaderText="Country" HeaderStyle-HorizontalAlign="Left">
<ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="tcountry" runat="server" Text='<%#Eval("country") %>'/>
</EditItemTemplate>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="TextBox4" runat="server"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Make Change" HeaderStyle-HorizontalAlign="Left">
<ItemTemplate>
<EditItemTemplate>
<asp:Button ID="Button1" runat="server" style="color: #800000;font-size: large" CommandName="up" Text="Update" />
<asp:Button ID="Button2" runat="server" style="color: #0000FF;font-size: large" CommandName="del" Text="Delete" />
<asp:Button ID="Button3" runat="server" style="color: #0000FF;font-size: large" CommandName="can" Text="Cancel" />
</EditItemTemplate>
</ItemTemplate>
<FooterTemplate>
<asp:Button ID="Button5" runat="server" style="color: #FF0000;font-size: large" CommandName="ins" Text="Insert"/>
</FooterTemplate>
<HeaderStyle HorizontalAlign="Left"></HeaderStyle>
</asp:TemplateField>
</Columns>
    <FooterStyle BackColor="#FFFFCC" ForeColor="#330099" />
<HeaderStyle BackColor="#990000" Font-Bold="True" ForeColor="#FFFFCC"></HeaderStyle>
    <PagerStyle BackColor="#FFFFCC" ForeColor="#330099" HorizontalAlign="Center" />
    <RowStyle BackColor="White" ForeColor="#330099" />
    <SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="#663399" />
    <SortedAscendingCellStyle BackColor="#FEFCEB" />
    <SortedAscendingHeaderStyle BackColor="#AF0101" />
    <SortedDescendingCellStyle BackColor="#F6F0C0" />
    <SortedDescendingHeaderStyle BackColor="#7E0000" />
</asp:GridView>
</div>
</form>
</body>
</html>

Step 4 :-Now click Design from the below of  Default.aspx page-->you will see following layout:-


grid-layout

Step 5 :- Now go properties of Gridview control-->Click Events-->Row command-->write command Name-->Double click on that for generating the handler as shown below:-
properties
Step 6 :- Now double click on the page(or press F7)-->write the following codes on default.aspx.cs page as shown below:-

using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
using System.IO;

public partial class gridview : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

        if (!IsPostBack)
        {
            GetData();
        }
    }

    private void GetData()
    {
SqlConnection con = new SqlConnection(@"Data Source=.\;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True;");
        con.Open();
        SqlCommand cmd = new SqlCommand("select*from student", con);
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        DataSet ds = new DataSet();
        da.Fill(ds);
        GridView1.DataSource = ds.Tables[0];
        GridView1.DataBind();
    }
    protected void gvDetails_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName == "ins")
        {
       TextBox name = (TextBox)GridView1.FooterRow.FindControl("TextBox2");
       TextBox age = (TextBox)GridView1.FooterRow.FindControl("TextBox3");
       TextBox country = (TextBox)GridView1.FooterRow.FindControl("TextBox4");
SqlConnection con = new SqlConnection(@"Data Source=.;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True;Max Pool Size=20; Connection Timeout=10;");
            con.Open();
SqlCommand cmd = new SqlCommand("insert into student values('" + name.Text + "','" + age.Text + "','" + country.Text + "')", con);
            int i = cmd.ExecuteNonQuery();
            if (i > 0)
            {
                Label1.Text = "Recard inserted successfully....";
                GetData();
            }
        }
        else if (e.CommandName == "up")
        {
SqlConnection con2 = new SqlConnection(@"Data Source=.;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True;Max Pool Size=20; Connection Timeout=10;");
            con2.Open();
 GridViewRow grid1 = (GridViewRow)((Button)e.CommandSource).NamingContainer;
            Label sid = (Label)grid1.FindControl("lsid");
            TextBox name = (TextBox)grid1.FindControl("tname");
            TextBox age = (TextBox)grid1.FindControl("tage");
            TextBox country = (TextBox)grid1.FindControl("tcountry"); SqlCommand cmd = new SqlCommand("update student set name='" + name.Text + "',age='" + age.Text + "',country='" + country.Text + "' where sid ='" + sid.Text + "'", con2);
            int i = cmd.ExecuteNonQuery();
            if (i > 0)
            {
                Label1.Text = "Recard Updated successfully....";
                GetData();
            }
        }
        else if (e.CommandName == "del")
        {
GridViewRow grid1 = (GridViewRow)((Button)e.CommandSource).NamingContainer;
SqlConnection con1 = new SqlConnection(@"Data Source=.;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True;Max Pool Size=20; Connection Timeout=10;");
            con1.Open();
            Label sid = (Label)grid1.FindControl("lsid");
SqlCommand cmd = new SqlCommand("delete from student where sid='" + sid.Text + "'", con1);
            int i = cmd.ExecuteNonQuery();
            if (i > 0)
            {
                Label1.Text = "Recard Deleted successfully....";
                GetData();
            }
        }
        else if (e.CommandName == "del")
        {
            GridView1.EditIndex=-1;
                GetData();
            }
        }
    protected void LinkButton1_Click(object sender, EventArgs e)
    {
        Response.Redirect("print.aspx");
    }
}

Step 7 :- Now Add another web form (print.aspx)-->click Source button -->and write Gridview layout codes (html and java script) as given below:-

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="ptrint.aspx.cs" Inherits="ptrint" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title></title>
    <script type="text/javascript">
        function print_page() {
            window.print();
        } 
    </script>
    <style type="text/css">
        .Gridview
        {}
    </style>
</head>
<div>
<a href="#" onclick="javascript :print_page();"><strong><span class="style1">Take print out</span></strong></a>
</div>
<body>
<form id="form1" runat="server">
<div>
    <asp:Label ID="Label1" runat="server" style="color: #800000" Text="*"></asp:Label>
<asp:GridView ID="GridView1" DataKeyNames="sid" runat="server"
AutoGenerateColumns="False" CssClass="Gridview" HeaderStyle-BackColor="#FFFFF"
ShowFooter="True" HeaderStyle-Font-Bold="true" HeaderStyle-ForeColor="White" 
        Width="898px" Height="231px" CellPadding="4" ForeColor="#333333" 
        GridLines="None">
    <AlternatingRowStyle BackColor="White" />
<Columns>
<asp:TemplateField HeaderText="Sid" HeaderStyle-HorizontalAlign="Left">
<ItemTemplate>
<EditItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%#Eval("sid") %>'/>
</EditItemTemplate>
</ItemTemplate>
<FooterTemplate>
</FooterTemplate>
<HeaderStyle HorizontalAlign="Left"></HeaderStyle>
</asp:TemplateField>
<asp:TemplateField HeaderText="Name" HeaderStyle-HorizontalAlign="Left">
<ItemTemplate>
<EditItemTemplate>
<asp:Label ID="Label2" runat="server" Text='<%#Eval("name") %>'/>
</EditItemTemplate>
</ItemTemplate>
<FooterTemplate>
</FooterTemplate>
<HeaderStyle HorizontalAlign="Left"></HeaderStyle>
</asp:TemplateField>
<asp:TemplateField HeaderText="Age" HeaderStyle-HorizontalAlign="Left">
<ItemTemplate>
<EditItemTemplate>
<asp:Label ID="Label3" runat="server" Text='<%#Eval("age") %>'/>
</EditItemTemplate>
</ItemTemplate>
<FooterTemplate>
</FooterTemplate>
<HeaderStyle HorizontalAlign="Left"></HeaderStyle>
</asp:TemplateField>
<asp:TemplateField HeaderText="Country" HeaderStyle-HorizontalAlign="Left">
<ItemTemplate>
<EditItemTemplate>
<asp:Label ID="Label4" runat="server" Text='<%#Eval("country") %>'/>
</EditItemTemplate>
</ItemTemplate>
<FooterTemplate>
</FooterTemplate>
<HeaderStyle HorizontalAlign="Left"></HeaderStyle>
</asp:TemplateField>
</Columns>
    <FooterStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#990000" Font-Bold="True" ForeColor="White"></HeaderStyle>
    <PagerStyle BackColor="#FFCC66" ForeColor="#333333" HorizontalAlign="Center" />
    <RowStyle BackColor="#FFFBD6" ForeColor="#333333" />
    <SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="Navy" />
    <SortedAscendingCellStyle BackColor="#FDF5AC" />
    <SortedAscendingHeaderStyle BackColor="#4D0000" />
    <SortedDescendingCellStyle BackColor="#FCF6C0" />
    <SortedDescendingHeaderStyle BackColor="#820000" />
</asp:GridView>
</div>
</form>
</body>
</html>

Description:- In above codes i have explained how to take preview of Gridview data and print it.In above codes i have written script code  in <head> section for printing the Gridview data as given below:-
?
1
2
3
4
5
6
7
8
9
<html>
<head>
    <title></title>
    <script type="text/javascript">
         function print_page() {
             window.print();
         }
    </script>
</head>
Now i have called this script function from the <body> section on clicking button(Take Print out) as given below:
?
1
2
3
4
5
6
7
<body>
<form>
<div>
<a href="#" onclick="javascript :print_page();"><strong><span class="style1">Take print out</span></strong></a>
</div>
</form>
</body>

Step 8 :- Now click design --> You will see following layout as shown below:-


print_layout

Step 9 :- Now Double click on print.aspx page(or press F7)-->Write the following codes on print.aspx.cs page  as given below

using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
using System.IO;
public partial class ptrint : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            GetData();
        }
    }
    private void GetData()
    {
        SqlConnection con = new SqlConnection(@"Data Source=.\;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True;");
        con.Open();
        SqlCommand cmd = new SqlCommand("select*from student", con);
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        DataSet ds = new DataSet();
        da.Fill(ds);
        GridView1.DataSource = ds.Tables[0];
        GridView1.DataBind();
    }
}

Step 10 :-  Now Run the Application(press F5)-->Follow the following points to run the Gridview application perfectly,Which are given below:-
  • Write the Name,age and country fields values in below Text Box as shown below-->Press Insert button.
Insert

  • Now Update record sid =101 in Gridview as shown below:-
delete_records
  • Now Delete the record sid=103 as shown below:-
delete_records


  • If you want to Edit one by one row at a time then you can use following Edit handler codes as given below.

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


  • Now click Take Preview Button -->You will see following as shown below:-
preview


  • Now click Take Print out Button -->You can take print out of the Existing page as shown below:-
print out


Note:- You can save this above file data in .PDF extension also.(click change -->save as pdf-->save). 

I hope this helpful for you.
For More..
  1. How to make Ajax based Custom registration page in asp.net
  2. How to make Ado.net Application
  3. How to create captcha image in asp.net
  4. How to create setup file with Database
  5. Navigation Application in asp.net
  6. How to use session state in asp.net application
  7. Microsoft Sql Server commands and its usage
  8. oops concepts in C#
  9. Multithreading application in C#
  10. File handling real Application

Click below for Download whole application

                 Download

1 comment:

  1. In Step-6
    in line no.55 and 76 put "sid" instead of "lsid".
    Then it'll work properly.

    ReplyDelete

Powered by Blogger.