Wednesday 4 April 2012

Grid View Events


Introduction:

In this article I will explain how to insert, edit, update and delete data in gridview using asp.net.
I have tried to make the normal Add (Insert), Edit, Update and delete functions in ASP.Net Grid View simple and also combining the powers of ASP.Net AJAX with that of JQuery to give an elegant and charming user experience. I have used some of gridview events those are 
           1) Onrowcancelingedit
           2) Onrowediting
           3) Onrowupdating
           4) Onrowcancelingedit
      5) Onrowdeleting

 Create a data base table with name grid view
Column Name
Data Type
Empid
Int(set identity property=true)
First name
varchar(50)
Last name
varchar(50)
Title
varchar(50)
Country
varchar(50)

Create Store procedures for insert, delete ,update

After completion table creation design aspx page like this
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:ScriptManager ID="ScriptManager1" runat="server">
        </asp:ScriptManager>
              
        <asp:GridView ID="GridView1" runat="server" onrowcancelingedit="GridView1_RowCancelingEdit"
   onrowediting="GridView1_RowEditing" onrowupdating="GridView1_RowUpdating"
               AutoGenerateColumns="False" CellPadding="4" ForeColor="#333333"
               GridLines="None" onselectedindexchanged="GridView1_SelectedIndexChanged"
               ShowFooter="True" Width="839px">
            <AlternatingRowStyle BackColor="White" />
        <Columns>
        <asp:TemplateField HeaderText="Empid">
        <ItemTemplate>
        <asp:Label runat="server" ID ="lbempid" Text='<%# Eval("Empid") %>'></asp:Label>
        </ItemTemplate>
        <EditItemTemplate >
                <asp:TextBox ID="txtEmpid" Text ='<%# Eval("Empid") %>' runat="server"></asp:TextBox>
            </EditItemTemplate>
        <FooterTemplate>
        <asp:TextBox runat="server" ID="txtEmpid"></asp:TextBox>
        </FooterTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Lastname">
        <ItemTemplate>
            <asp:Label ID="lbLastname" runat="server" Text='<%# Eval("Lastname") %>'></asp:Label>
            </ItemTemplate>
            <EditItemTemplate >
                <asp:TextBox ID="txtLastname" Text ='<%# Eval("Lastname") %>' runat="server"></asp:TextBox>
            </EditItemTemplate>
            <FooterTemplate>
                <asp:TextBox ID="txtLastname" runat="server"></asp:TextBox>
            </FooterTemplate>
            </asp:TemplateField>

            <asp:TemplateField HeaderText="Firstname">
        <ItemTemplate>
            <asp:Label ID="lbFirstname" runat="server" Text='<%# Eval("Firstname") %>'></asp:Label>
            </ItemTemplate>
            <EditItemTemplate >
                <asp:TextBox ID="txtFirstname" Text ='<%# Eval("Firstname") %>' runat="server"></asp:TextBox>
            </EditItemTemplate>
            <FooterTemplate>
                <asp:TextBox ID="txtFirstname" runat="server"></asp:TextBox>
            </FooterTemplate>
            </asp:TemplateField>
           
             <asp:TemplateField HeaderText="Title">
        <ItemTemplate>
            <asp:Label ID="lbTitle" runat="server" Text='<%# Eval("Title") %>'></asp:Label>
            </ItemTemplate>
            <EditItemTemplate >
                <asp:TextBox ID="txtTitle" Text ='<%# Eval("Title") %>' runat="server"></asp:TextBox>
            </EditItemTemplate>
            <FooterTemplate>
                <asp:TextBox ID="txtTitle" runat="server"></asp:TextBox>
            </FooterTemplate>
            </asp:TemplateField>

            <asp:TemplateField HeaderText="Country">
        <ItemTemplate>
            <asp:Label ID="lbCountry" runat="server" Text='<%# Eval("Country") %>'></asp:Label>
            </ItemTemplate>
            <EditItemTemplate >
                <asp:TextBox ID="txtCountry" Text ='<%# Eval("Country") %>' runat="server"></asp:TextBox>
            </EditItemTemplate>
            <FooterTemplate>
                <asp:TextBox ID="txtCountry" runat="server"></asp:TextBox>
            </FooterTemplate>
            </asp:TemplateField>
             <%--OnClientClick = "return confirm('Do you want to delete?')"--%>
            <asp:TemplateField>
               <ItemTemplate>
        <asp:LinkButton ID="LinkButton1" runat="server" OnClick ="Deleteemployee" CommandArgument = '<%# Eval("Empid")%>'>Delete</asp:LinkButton>
                               </ItemTemplate>
        <FooterTemplate>
            <asp:Button ID="Button1" runat="server" Text="Add" OnClick ="Add" />
            </FooterTemplate>
</asp:TemplateField>
<asp:CommandField ShowEditButton="true" />
        </Columns>
            <EditRowStyle BackColor="#7C6F57" />
            <FooterStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White" />
            <HeaderStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White" />
            <PagerStyle BackColor="#666666" ForeColor="White" HorizontalAlign="Center" />
            <RowStyle BackColor="#E3EAEB" />
            <SelectedRowStyle BackColor="#C5BBAF" Font-Bold="True" ForeColor="#333333" />
            <SortedAscendingCellStyle BackColor="#F8FAFA" />
            <SortedAscendingHeaderStyle BackColor="#246B61" />
            <SortedDescendingCellStyle BackColor="#D4DFE1" />
            <SortedDescendingHeaderStyle BackColor="#15524A" />
            <AlternatingRowStyle BackColor="#C2D69B"  />
        </asp:GridView>
       
    </div>
    </form>
</body>
</html>
After that add these namcespace using System.Data and using System.Data.SqlClient in your codebehind and write the following code

using System.Data.SqlClient;
using System.Data;
public partial class gridevents : System.Web.UI.Page
{
SqlConnection con = new SqlConnection ("Data Source=SHAILAJA;Initial Catalog=peers;User
                                                                                                                    ID=sa;Password=123");
    CommonClass cls = new CommonClass();
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            BindData();                  
        } }
        private void BindData()
    {
        con.Open();
        SqlDataAdapter sda = new SqlDataAdapter("select * from gridview", con);
        DataTable table = new DataTable();
        sda.Fill(table);
        GridView1.DataSource = table;
        GridView1.DataBind();
    }   
    protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
    {
        GridView1.EditIndex = e.NewEditIndex;
        BindData();
    }
    protected void Deleteemployee(object sender, EventArgs e)
    {     
           Hashtable ht = new Hashtable();
        ht.Add("@ID",((TextBox)GridView1.FooterRow.FindControl("txtEmpid")).Text);
        int result = cls.ExecuteQuery("deletegrid", ht);
        if (result > 0)
        {
            string msg = "<script>alert('deleted sucessfully')</script>";
            ScriptManager.RegisterStartupScript(this, typeof(Control), "alertmsg", msg, false);
        }
                BindData();
    }
    protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
               Hashtable ht = new Hashtable();
        ht.Add("@ID", ((TextBox)GridView1.FooterRow.FindControl("txtEmpid")).Text);
        ht.Add("@Firstname", ((TextBox)GridView1.FooterRow.FindControl("txtFirstname")).Text);
        ht.Add("@Lastname", ((TextBox)GridView1.FooterRow.FindControl("txtLastname")).Text);
        ht.Add("@Title", ((TextBox)GridView1.FooterRow.FindControl("txtTitle")).Text);
        ht.Add("@Country", ((TextBox)GridView1.FooterRow.FindControl("txtCountry")).Text);
        int result = cls.ExecuteQuery("updategrid", ht);
        if (result > 0)
        {
            string msg = "<script>alert('updated sucessfully')</script>";
            ScriptManager.RegisterStartupScript(this, typeof(Control), "alertmsg", msg, false);
        }
        GridView1.EditIndex = -1;
        BindData();
    }
    protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {
        GridView1.EditIndex = -1;
        BindData();
    }
    protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
    {
        BindData();
    }
    protected void Add(object sender,EventArgs e)
    {
               Hashtable ht = new Hashtable();
        ht.Add("@ID", ((TextBox)GridView1.FooterRow.FindControl("txtEmpid")).Text);
        ht.Add("@Firstname", ((TextBox)GridView1.FooterRow.FindControl("txtFirstname")).Text);
        ht.Add("@Lastname", ((TextBox)GridView1.FooterRow.FindControl("txtLastname")).Text);
        ht.Add("@Title", ((TextBox)GridView1.FooterRow.FindControl("txtTitle")).Text);
        ht.Add("@Country", ((TextBox)GridView1.FooterRow.FindControl("txtCountry")).Text);
        int result = cls.ExecuteQuery("grid", ht);
        if (result > 0)
        {
            string msg = "<script>alert('inserted sucessfully')</script>";
            ScriptManager.RegisterStartupScript(this, typeof(Control), "alertmsg", msg, false);
        }
        BindData();
          }
    }


Add class to your solution and write the following code
public class CommonClass
{
public int ExecuteQuery(string procName, Hashtable parms)
    {
        SqlCommand cmd = new SqlCommand();
      
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.CommandText = procName;
        if (parms.Count > 0)
        {
            foreach (DictionaryEntry de in parms)
            {
                    cmd.Parameters.AddWithValue(de.Key.ToString(), de.Value);
            }
}       }

Demo:

No comments:

Post a Comment