Insert,Update,Delete in GridView Using Asp.Net C#

INSERT,UPDATE ,DELETE in GRIVIEW


Gridview control is used to populate the data in tabular format from different datasources and basically it derived from webcontrol class.

 Actually Gridview control is built with Many of features and this control is commonly used for all asp.net applications. 



DEMO





HTML Coding

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <table><tr><td colspan="2">
        </td></tr>
        <tr><td>
            <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" OnRowCancelingEdit="GridView1_RowCancelingEdit" OnRowDeleting="GridView1_RowDeleting"
OnRowEditing="GridView1_RowEditing"
 OnRowUpdating="GridView1_RowUpdating">
                <Columns>
                    <asp:CommandField ShowEditButton="True" />
                    <asp:CommandField ShowDeleteButton="True" />
                    <asp:TemplateField HeaderText="Name">
                        <EditItemTemplate>
                            <asp:Label ID="lblNameUpdate" runat="server" Text='<%# Eval("name") %>'></asp:Label> 
                            </EditItemTemplate>
                        <ItemTemplate>
                            <asp:Label ID="lblNameDelete" runat="server" Text='<%# Eval("name") %>'></asp:Label>
                        </ItemTemplate>
                    </asp:TemplateField>
                    <asp:TemplateField HeaderText="Email ID">
                        <EditItemTemplate>
                            <asp:TextBox ID="txtEmailID" runat="server" Text='<%# Eval("email") %>'></asp:TextBox>
                        </EditItemTemplate>
                        <ItemTemplate>
                            <asp:Label ID="Label2" runat="server" Text='<%# Eval("email") %>'></asp:Label>
                        </ItemTemplate>
                    </asp:TemplateField>
                    <asp:TemplateField HeaderText="Mobile Number">
                        <EditItemTemplate>
                            <asp:TextBox ID="txtMobileNumber" runat="server" Text='<%# Eval("mobile") %>'></asp:TextBox>
                        </EditItemTemplate>
                        <ItemTemplate>
                            <asp:Label ID="Label3" runat="server" Text='<%# Eval("mobile") %>'></asp:Label>
                        </ItemTemplate>
                    </asp:TemplateField>
                    <asp:TemplateField HeaderText="UserName">
                        <EditItemTemplate>
                            <asp:TextBox ID="txtUserName" runat="server" Text='<%# Eval("username") %>'></asp:TextBox>
                        </EditItemTemplate>
                        <ItemTemplate>
                            <asp:Label ID="Label4" runat="server" Text='<%# Eval("username") %>'></asp:Label>
                        </ItemTemplate>
                    </asp:TemplateField>
                    <asp:TemplateField HeaderText="Password">
                        <EditItemTemplate>
                            <asp:TextBox ID="txtPassword" runat="server" Text='<%# Eval("password") %>'></asp:TextBox>
                        </EditItemTemplate>
                        <ItemTemplate>
                            <asp:Label ID="Label5" runat="server" Text='<%# Eval("password") %>'></asp:Label>
                        </ItemTemplate>
                    </asp:TemplateField>
                </Columns>
            </asp:GridView>
            &nbsp;</td></tr>

    </table>
    </div>
    </form>
</body>
</html>

    
C#  Coding


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;

public partial class InsertUpdateDelete : System.Web.UI.Page
{
    SqlConnection con;
    SqlCommand cmd;
    SqlDataAdapter adp;
    SqlDataReader rd;
    DataSet ds;
    string query;

    public void dbcon()
    {
        string connn = (System.Configuration.ConfigurationManager.ConnectionStrings["dbcon"].ToString());
        con = new SqlConnection(connn);
        con.Open();

    }
  

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

        }
    }   
    protected void bind199()
    {
        dbcon();
        query = "select * from register";
        cmd = new SqlCommand(query, con);
        adp = new SqlDataAdapter(cmd);
        ds = new DataSet();
        adp.Fill(ds);
         rd = cmd.ExecuteReader();
         if (ds.Tables[0].Rows.Count > 0)
         {
             GridView1.DataSource = ds;
             GridView1.DataBind();
         }
         else
         {
             ds.Tables[0].Rows.Add(ds.Tables[0].NewRow());
             GridView1.DataSource = ds;
             GridView1.DataBind();
             int columncount = GridView1.Rows[0].Cells.Count;
             GridView1.Rows[0].Cells.Clear();
             GridView1.Rows[0].Cells.Add(new TableCell());
             GridView1.Rows[0].Cells[0].ColumnSpan = columncount;
             GridView1.Rows[0].Cells[0].Text = "No Records Found";
         }
    }


    protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {
        GridView1.EditIndex = -1;
        bind199();
    }
    protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
    {
        GridView1.EditIndex = e.NewEditIndex;
        bind199();
    }
    protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        dbcon();

        Label lblname = (Label)GridView1.Rows[e.RowIndex].FindControl("lblNameUpdate");
        TextBox txtemail = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txtEmailID");
        TextBox txtmobile = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txtMobileNumber");
        TextBox txtusername = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txtUserName");
        TextBox txtpassword = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txtPassword");
        
query = "update register set email='"+txtemail.Text+"',mobile='"+txtmobile.Text+"',username='"+txtusername.Text+"',
password='"+txtpassword.Text+"' where name='"+lblname.Text+"'";

        cmd = new SqlCommand(query, con);
        cmd.ExecuteNonQuery();
        Response.Write("<script>alert('Data Updated')</script>");
        GridView1.EditIndex = -1;
        bind199();
    }
    protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        dbcon();

        Label lblname1 = (Label)GridView1.Rows[e.RowIndex].FindControl("lblNameDelete");
        query = "delete from register where name='" + lblname1.Text + "'";
        cmd=new SqlCommand (query,con);
        cmd.ExecuteNonQuery();
        Response.Write("<script>alert('Data Deleted')</script>");
        bind199();

    }
}




 Admin  can view the registered users on the website, but when an admin wants to edit or delete any  duplicate or Unwanted data from the table there is a method in GridView to edit, delete and update.

some of gridview events those are 

1.Onrowcancelingedit
2.Onrowediting
3.Onrowupdating
4.Onrowdeleting





First - Create the Database table for register   &  Insert Some Values for register table

Add the Gridview from Tool Box






Next - Gridview Edit Column button click -  & Remove - Auto Generate Field







Next  - Select Command Field  & Select  the Edit,update,cancel button  &  Click - Add Button








Next - Select Delete Button   &  Click - Add Button 








Next - Add - TemplateField - for Required 







Next - Change the Header Text from All Template Fields  

Header Text Only Display Name  Fill Your Wise








Next  - Add Column Name & Edit ,Delete Command Button 










Next - Select - Gridview  Edit Templates







                
       Next - Select  Column from  GridView Task  - Select Label                 to Item Template







Next - Select Label - Edit DataBinding -  Coding to Database table Field Name  Eval("your field name")- ok button click









Next - Select Label - Edit DataBinding -  Coding to Database table Field Name  Eval("your field name")- OK - button Click










Next - Select Label - Edit DataBinding -  Coding to Database table Field Name  Eval("your field name")- OK Button Click










Next - Select Label - Edit DataBinding -  Coding to Database table Field Name  Eval("your field name")- OK Button Click








Next - Select Label - Edit DataBinding -  Coding to Database table Field Name  Eval("your field name")- OK Button Click








Next - add label to EditItemTemplate - Select Label - Edit DataBinding -  Coding to Database table Field Name  Eval("your field name")- OK Button Click







Next - add Textbox to EditItemTemplate - Select Textbox - Edit DataBinding -  Coding to Database table Field Name  Eval("your field name")- and OK Button Click








 id  values give to label 







Next - add Textbox to EditItemTemplate - Select Textbox - Edit DataBinding -  Coding to Database table Field Name  Eval("your field name")- and OK Button Click   









id  values give to Textbox 







Next - add Textbox to EditItemTemplate - Select Textbox - Edit DataBinding -  Coding to Database table Field Name  Eval("your field name")- and OK Button Click 







id  values give to Textbox 





Next - Add Textbox to EditItemTemplate - Select Textbox - Edit DataBinding -  Coding to Database table Field Name  Eval("your field name")- and OK Button Click 
  





id  values give to Textbox 






Next - add Textbox to EditItemTemplate - Select Textbox - Edit DataBinding -  Coding to Database table Field Name  Eval("your field name")- and OK Button Click







id  values give to Textbox 





                 
                   
                   Next  - Click  End Template Editing







Next  - All  Databind from register table fields





                                               
                                                HTML Coding









Next - Double Click Empty Page or Go to Coding Page






   
             Add the Namespaces -  Database Connection  







Select - All Register Table data's  using Select Query -  page_load  function  give to IsPostBack  Condition to avoid Every  time Postback the values







 Next - Select   Gridview property -  Select Event Double Click -  Related Events Shown













 
Next - Select  RowCancelingEdit event for editing time calcel function







Write Below Coding  & IsPostBack Values Call






 Next - Select  RowEditing event for edit binding Values 







Write Below Coding  & IsPostBack Values Call






 Next - Select  RowUpdateing event for Update the  binding Values 






Row - Updating  all Fields Where Condition for name in EditItemTable  







Where  Condition use Edit item Template  name











Findcontrol  use Gridview EditItemTemplate









































                         
                        Next - Select Row Deleting Event







Find Control  Select Id from ItemTemplate  Lable ID



















OUTPUT

  Next  - F5 Click -   Run the Program  Show  the table Values 







Select -  Edit Button  Open  Values From Textbox for Edit & Update - Insert  Some Values - where Condition Use  name that's can not Update 








Next  - Press Update Button Data Updated 







Next - Delete Button Press Delete the Name Field Where Condition used Name







Next  - Dleted  one Record














Next - Edit Button Press - No need to Edit or Change Values  - Click Cancel Button 







Canceling  







0 comments:

Post a Comment