Insert, Edit, update, delete data in gridview using asp.net

Insert, Edit, update, delete data in gridview using asp.net Introduction:

In this example i'm going to explain how to insert,Edit, update ,delete data in gridview in  asp.net.

If you want to check all the example in my site please check this link Ajax all extenders examples and also you check my previous example how to give paging to Datalist in asp.net

 

First we need to design the table in Database and give the table name as "Data".


Column Name Datatype
PID int(set identity property=true)
UserName nvarchar(50)
FirstName nvarchar(50)
SecondName nvarchar(50)
Age int
FatherName nvarchar(50)

  Your aspx page should be like this


<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <asp:GridView ID="grdDetails" runat="server" AutoGenerateColumns="False"                                 OnRowEditing="grdDetails_RowEditing"
                      OnRowCancelingEdit="grdDetails_RowCancelingEdit"                                           OnRowCommand="grdDetails_RowCommand"                                
            OnRowDeleting="grdDetails_RowDeleting" OnRowUpdating="grdDetails_RowUpdating"
            CellPadding="4" ForeColor="#333333" GridLines="None" ShowFooter="true">
    <AlternatingRowStyle BackColor="White" />
    <Columns>
    
    <asp:TemplateField HeaderText="Action">
    <ItemTemplate>
    <asp:LinkButton ID="lnkbtnEdit" runat="server" Text="Edit" CommandName="Edit" />
    <asp:LinkButton ID="lnkbtnDelete" runat="server" Text="Delete" CommandName="Delete" />
    </ItemTemplate>
    
    <EditItemTemplate>
    <asp:LinkButton ID="lnkbtnUpdate" runat="server" Text="Update" CommandName="Update" />
   <asp:LinkButton ID="lnkbtncancel" runat="server" Text="Cancels" CommandName="Cancel" />
    </EditItemTemplate>
    
    <FooterTemplate>
    <asp:Button ID="btnadd" runat="server" Text="Add" CommandName="Insert" />
    </FooterTemplate>
    </asp:TemplateField>
    <asp:TemplateField HeaderText=" User Name">
    <ItemTemplate>
    <asp:Label ID="lblUserName" runat="server" Text='<%# Eval("UserName")%>'></asp:Label>
    </ItemTemplate>
    <FooterTemplate>
    <asp:TextBox ID="txtftUserName" runat="server" Text=""></asp:TextBox>
    </FooterTemplate>
    </asp:TemplateField>
    <asp:TemplateField HeaderText=" First Name">
    
   <ItemTemplate>
   <asp:Label ID="lblFirstName" runat="server" Text='<%# Eval("FirstName")%>'></asp:Label>
    </ItemTemplate>
    <EditItemTemplate>
   <asp:TextBox ID="txtFirstName" runat="server" Text='<%# Eval("FirstName")%>'>              </asp:TextBox>
   </EditItemTemplate>
   <FooterTemplate>
   <asp:TextBox ID="txtftFirstName" runat="server" Text=""></asp:TextBox>
   </FooterTemplate>
   </asp:TemplateField>
  <asp:TemplateField HeaderText="Second Name">
  
  <ItemTemplate>
  <asp:Label ID="lblSecondName" runat="server" Text='<%# Eval("SecondName")%>'>             </asp:Label>
  </ItemTemplate>
  
  <EditItemTemplate>
  <asp:TextBox ID="txtSecondName" runat="server" Text='<%# Eval("SecondName")%>'>          </asp:TextBox>
  </EditItemTemplate>
  <FooterTemplate>
  <asp:TextBox ID="txtftSecondName" runat="server" Text=""></asp:TextBox>
  </FooterTemplate>
  </asp:TemplateField>
  <asp:TemplateField HeaderText="Age">
  <ItemTemplate>
  <asp:Label ID="lblAge" runat="server" Text='<%# Eval("Age")%>'></asp:Label>
  </ItemTemplate>
  <EditItemTemplate>
  <asp:TextBox ID="txtAge" runat="server" Text='<%# Eval("Age")%>'></asp:TextBox>
  </EditItemTemplate>
  <FooterTemplate>
  <asp:TextBox ID="txtftAge" runat="server" Text=""></asp:TextBox>
  </FooterTemplate>
  </asp:TemplateField>


  <asp:TemplateField HeaderText="Father Name">
  <ItemTemplate>
  <asp:Label ID="lblFatherName" runat="server" Text='<%# Eval("FatherName")%>'> </asp:Label>
  </ItemTemplate>
  <EditItemTemplate>
  <asp:TextBox ID="txtFatherName" runat="server" Text='<%# Eval("FatherName")%>'></asp:TextBox>
  </EditItemTemplate>
  <FooterTemplate>
   <asp:TextBox ID="txtftFatherName" runat="server" Text=""></asp:TextBox>
   </FooterTemplate>
  </asp:TemplateField>
   </Columns>
          
        </asp:GridView>
       
    </div>
    </form>
</body>
</html>
In the above gridview you have to take below events

OnRowEditing
OnRowCancelingEdit
OnRowCommand
OnRowDeleting
OnRowUpdating
Your Aspx.cs page like this
 

using System;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Drawing;
using System.Web.UI.WebControls;
using System.Text;
using System.Web.UI;
public partial class aspexamples_grid : System.Web.UI.Page
{
    SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["connectionStr"].ConnectionString);

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {

            getGridDetails();
        }
    }

    private void getGridDetails()
    {
        try
        {

            string fetchQuery = "select * from Data";
            SqlCommand cmd = new SqlCommand(fetchQuery, con);
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            DataSet ds = new DataSet();
            da.Fill(ds);

            if (ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
            {
                grdDetails.DataSource = ds;
                grdDetails.DataBind();
            }
            else
            {
                ds.Tables[0].Rows.Add(ds.Tables[0].NewRow());
                grdDetails.DataSource = ds;
                grdDetails.DataBind();
                int columncount = grdDetails.Rows[0].Cells.Count;
                grdDetails.Rows[0].Cells.Clear();
                grdDetails.Rows[0].Cells.Add(new TableCell());
                grdDetails.Rows[0].Cells[0].ColumnSpan = columncount;
                grdDetails.Rows[0].Cells[0].Text = "No Records Found";
                grdDetails.Rows[0].Cells[0].Attributes.CssStyle["text-align"] = "Center";
            }
        }
        catch (Exception ex)
        {

            throw ex;
        }

    }


    protected void grdDetails_RowEditing(object sender, GridViewEditEventArgs e)
    {
        grdDetails.EditIndex = e.NewEditIndex;
        getGridDetails();

    }
    protected void grdDetails_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        Label LblUname = (Label)grdDetails.Rows[e.RowIndex].FindControl("lblUserName");
        con.Open();
        string fetchQuery = "Delete from Data where UserName='" + LblUname.Text + "'";
        SqlCommand cmd = new SqlCommand(fetchQuery, con);
        int count = cmd.ExecuteNonQuery();
        if (count == 1)
        {
            ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "Alert",               "alert('User Details Succesfully deleted.')", true);
            getGridDetails();
        }
        else
        {
            ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "Alert",               "alert('Deletion Failed.')", true);
        }


    }
  protected void grdDetails_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {
        grdDetails.EditIndex = -1;
        getGridDetails();
    }
    protected void grdDetails_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        Label LblUname = (Label)grdDetails.Rows[e.RowIndex].FindControl("lblUserName");
        TextBox txtFirstName = (TextBox)grdDetails.Rows[e.RowIndex].FindControl("txtFirstName");
        TextBox txtSecondName = (TextBox)grdDetails.Rows[e.RowIndex].FindControl("txtSecondName");
        TextBox txtAge = (TextBox)grdDetails.Rows[e.RowIndex].FindControl("txtAge");
        TextBox txtFatherName = (TextBox)grdDetails.Rows[e.RowIndex].FindControl("txtFatherName");

        String UpdateQuery = "Update Data set FirstName='" + txtFirstName.Text + "',SecondName='" + txtSecondName.Text + "',Age=" + txtAge.Text + ",FatherName='" + txtFatherName.Text + "'  where UserName='" + LblUname.Text + "'";
        SqlCommand cmd = new SqlCommand(UpdateQuery, con);
        con.Open();
        int i = cmd.ExecuteNonQuery();
        con.Close();

        if (i == 1)
        {
            ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "Alert",              "alert('User details sucessfully updated.')", true);
        }
        grdDetails.EditIndex = -1;
        getGridDetails();


    }

    protected void grdDetails_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName.Equals("Insert"))
        {
            TextBox txtUsrname = (TextBox)grdDetails.FooterRow.FindControl("txtftUserName");
            TextBox txtFirstName = (TextBox)grdDetails.FooterRow.FindControl("txtftFirstName");

            TextBox txtSecondName = (TextBox)grdDetails.FooterRow.FindControl("txtftSecondName");
            TextBox txtAge = (TextBox)grdDetails.FooterRow.FindControl("txtftAge");
            TextBox txtFatherNAme = (TextBox)grdDetails.FooterRow.FindControl("txtftFatherName");
            con.Open();
            SqlCommand cmd =
            new SqlCommand(
            "insert into Data(UserName,FirstName,SecondName,Age,FatherName) values('" + txtUsrname.Text + "','" +
            txtFirstName.Text + "','" + txtSecondName.Text + "','" + txtAge.Text + "','" + txtFatherNAme.Text + "')", con);
            int result = cmd.ExecuteNonQuery();
            con.Close();
            if (result == 1)
            {
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(),                        "Alert", "alert('User details sucessfully inserted.')", true);
                getGridDetails();
            }
            else
            {
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(),                      "Alert", "alert('User details insertion failed.')", true);
            }
        }

    }

}

1 comment:

adalvertooakes said...

How to find a legit casino site in PA - DRMCD
Pennsylvania 계룡 출장안마 is live 김제 출장마사지 with 부천 출장마사지 legal online 강릉 출장마사지 casinos, including Caesars Casino, FanDuel Casino, 구리 출장마사지 BetMGM Casino, Tropicana Casino, and others.