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

 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;

using System.Configuration;


namespace CRUD_GRIDVIEW

{

    public partial class _Default : Page

    {

        protected void Page_Load(object sender, EventArgs e)

        {

            if (!IsPostBack)

            {

                GridView1.DataSource = SqlDataSource1;

                GridView1.DataBind();

            }

        }


        protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)

        {

            GridView1.EditIndex = e.NewEditIndex;

            GridView1.DataSource = SqlDataSource1;

            GridView1.DataBind();

            Label6.Text = "";

            GridView1.EditRowStyle.BackColor = System.Drawing.Color.Orange;

        }


        protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)

        {

            GridView1.EditIndex = -1;

            GridView1.DataSource = SqlDataSource1;

            GridView1.DataBind();

            Label6.Text = "";

        }


        protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)

        {

            Label Id = GridView1.Rows[e.RowIndex].FindControl("Label5") as Label;

            TextBox name = GridView1.Rows[e.RowIndex].FindControl("TextBox1") as TextBox;

            TextBox gender = GridView1.Rows[e.RowIndex].FindControl("TextBox2") as TextBox;

            TextBox cl = GridView1.Rows[e.RowIndex].FindControl("TextBox3") as TextBox;

            string mycon = "Data Source=HEER\\SQLEXPRESS;Initial Catalog=Crud_Db;Integrated Security=True;Encrypt=False";

            string updatedata = "Update Student SET name='"+name.Text+"', gender='"+gender.Text+"', class='"+cl.Text+"' WHERE Id='"+Id.Text+"'";

            SqlConnection con = new SqlConnection(mycon);

            con.Open();

            SqlCommand cmd = new SqlCommand();

            cmd.CommandText = updatedata;

            cmd.Connection = con;

            cmd.ExecuteNonQuery();

            Label6.Text = "Row data has been updated successfully";

            GridView1.EditIndex = -1;

            SqlDataSource1.DataBind();

            GridView1.DataSource = SqlDataSource1;

            GridView1.DataBind();

        }


        protected void LinkButton5_Click(object sender, EventArgs e)

        {

            //TextBox Id = GridView1.FooterRow.FindControl("TextBox4") as TextBox;

            TextBox name = GridView1.FooterRow.FindControl("TextBox5") as TextBox;

            TextBox gender = GridView1.FooterRow.FindControl("TextBox6") as TextBox;

            TextBox cl = GridView1.FooterRow.FindControl("TextBox7") as TextBox;

            string query = "INSERT INTO Student(name,gender,class) VALUES('"+name.Text+"','"+gender.Text+"','"+cl.Text+"')";

            string mycon = "Data Source=HEER\\SQLEXPRESS;Initial Catalog=Crud_Db;Integrated Security=True;Encrypt=False";

            SqlConnection con = new SqlConnection(mycon);

            con.Open();

            SqlCommand cmd = new SqlCommand();

            cmd.CommandText = query;

            cmd.Connection = con;

            cmd.ExecuteNonQuery();

            Label6.Text = "New row inserted successfully";

            SqlDataSource1.DataBind();

            GridView1.DataSource = SqlDataSource1;

            GridView1.DataBind();

        }


        protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)

        {

            Label Id = GridView1.Rows[e.RowIndex].FindControl("Label1") as Label;

            string mycon = "Data Source=HEER\\SQLEXPRESS;Initial Catalog=Crud_Db;Integrated Security=True;Encrypt=False";

            string updatedata = "DELETE FROM Student WHERE Id=" + Id.Text;

            SqlConnection con = new SqlConnection(mycon);

            con.Open();

            SqlCommand cmd = new SqlCommand();

            cmd.CommandText = updatedata;

            cmd.Connection = con;

            cmd.ExecuteNonQuery();

            Label6.Text = "Row data has been deleted successfully";

            GridView1.EditIndex = -1;

            SqlDataSource1.DataBind();

            GridView1.DataSource = SqlDataSource1;

            GridView1.DataBind();

        }

    }

}

Above File is CRUD_GRIDVIEW\Default.aspx.cs











<%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="CRUD_GRIDVIEW._Default" %>


<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">


    <table class="w-100">

        <tr>

            <td>

                <asp:GridView ID="GridView1" runat="server" BackColor="#CCCCCC" BorderColor="#999999" BorderStyle="Solid" BorderWidth="3px" CellPadding="4" CellSpacing="2" ForeColor="Black" AutoGenerateColumns="False" ShowFooter="true" OnRowCancelingEdit="GridView1_RowCancelingEdit" OnRowDeleting="GridView1_RowDeleting" OnRowEditing="GridView1_RowEditing" OnRowUpdating="GridView1_RowUpdating">

                    <Columns>

                        <asp:TemplateField HeaderText="ID">

                            <EditItemTemplate>

                                <asp:Label ID="Label5" runat="server" Text='<%# Eval("Id") %>'></asp:Label>

                            </EditItemTemplate>

                            <FooterTemplate>

                                <asp:TextBox ID="TextBox4" runat="server"></asp:TextBox>

                            </FooterTemplate>

                            <ItemTemplate>

                                <asp:Label ID="Label1" runat="server" Text='<%# Eval("Id") %>'></asp:Label>

                            </ItemTemplate>

                            <ItemStyle HorizontalAlign="Center" />

                        </asp:TemplateField>

                        <asp:TemplateField HeaderText="Name">

                            <EditItemTemplate>

                                <asp:TextBox ID="TextBox1" runat="server" Text='<%# Eval("name") %>'></asp:TextBox>

                            </EditItemTemplate>

                            <FooterTemplate>

                                <asp:TextBox ID="TextBox5" runat="server"></asp:TextBox>

                            </FooterTemplate>

                            <ItemTemplate>

                                <asp:Label ID="Label2" runat="server" Text='<%# Eval("name") %>'></asp:Label>

                            </ItemTemplate>

                            <ItemStyle HorizontalAlign="Center" />

                        </asp:TemplateField>

                        <asp:TemplateField HeaderText="Gender">

                            <EditItemTemplate>

                                <asp:TextBox ID="TextBox2" runat="server" Text='<%# Eval("gender") %>'></asp:TextBox>

                            </EditItemTemplate>

                            <FooterTemplate>

                                <asp:TextBox ID="TextBox6" runat="server"></asp:TextBox>

                            </FooterTemplate>

                            <ItemTemplate>

                                <asp:Label ID="Label3" runat="server" Text='<%# Eval("gender") %>'></asp:Label>

                            </ItemTemplate>

                            <ItemStyle HorizontalAlign="Center" />

                        </asp:TemplateField>

                        <asp:TemplateField HeaderText="Class">

                            <EditItemTemplate>

                                <asp:TextBox ID="TextBox3" runat="server" Text='<%# Eval("class") %>'></asp:TextBox>

                            </EditItemTemplate>

                            <FooterTemplate>

                                <asp:TextBox ID="TextBox7" runat="server"></asp:TextBox>

                            </FooterTemplate>

                            <ItemTemplate>

                                <asp:Label ID="Label4" runat="server" Text='<%# Eval("class") %>'></asp:Label>

                            </ItemTemplate>

                            <ItemStyle HorizontalAlign="Center" />

                        </asp:TemplateField>

                        <asp:TemplateField HeaderText="Operations">

                            <EditItemTemplate>

                                <asp:LinkButton ID="LinkButton3" runat="server" CommandName="update">Update</asp:LinkButton>

                                &nbsp;

                                <asp:LinkButton ID="LinkButton4" runat="server" CommandName="Cancel">Cancel</asp:LinkButton>

                            </EditItemTemplate>

                            <FooterTemplate>

                                <asp:LinkButton ID="LinkButton5" runat="server" OnClick="LinkButton5_Click">Insert</asp:LinkButton>

                            </FooterTemplate>

                            <ItemTemplate>

                                <asp:LinkButton ID="LinkButton1" runat="server" CommandName="Edit">Edit</asp:LinkButton>

                                &nbsp;

                                <asp:LinkButton ID="LinkButton2" runat="server" CommandName="Delete">Delete</asp:LinkButton>

                            </ItemTemplate>

                            <ItemStyle HorizontalAlign="Center" />

                        </asp:TemplateField>

                    </Columns>

                    <FooterStyle BackColor="#CCCCCC" />

                    <HeaderStyle BackColor="Black" Font-Bold="True" ForeColor="White" />

                    <PagerStyle BackColor="#CCCCCC" ForeColor="Black" HorizontalAlign="Left" />

                    <RowStyle BackColor="White" />

                    <SelectedRowStyle BackColor="#000099" Font-Bold="True" ForeColor="White" />

                    <SortedAscendingCellStyle BackColor="#F1F1F1" />

                    <SortedAscendingHeaderStyle BackColor="#808080" />

                    <SortedDescendingCellStyle BackColor="#CAC9C9" />

                    <SortedDescendingHeaderStyle BackColor="#383838" />

                </asp:GridView>

            </td>

            <td></td>

        </tr>

        <tr>

            <td></td>

            <td></td>

        </tr>

        <tr>

            <td>

                <asp:Label ID="Label6" runat="server"></asp:Label>

            </td>

            <td></td>

        </tr>

        <tr>

            <td></td>

            <td></td>

        </tr>

        <tr>

            <td></td>

            <td></td>

        </tr>

        <tr>

            <td>

                <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:Crud_DbConnectionString2 %>" DeleteCommand="DELETE FROM [Student] WHERE [Id] = @Id" InsertCommand="INSERT INTO [Student] ([name], [gender], [class]) VALUES (@name, @gender, @class)" ProviderName="<%$ ConnectionStrings:Crud_DbConnectionString2.ProviderName %>" SelectCommand="SELECT * FROM [Student]" UpdateCommand="UPDATE [Student] SET [name] = @name, [gender] = @gender, [class] = @class WHERE [Id] = @Id">

                    <DeleteParameters>

                        <asp:Parameter Name="Id" Type="Int32" />

                    </DeleteParameters>

                    <InsertParameters>

                        <asp:Parameter Name="name" Type="String" />

                        <asp:Parameter Name="gender" Type="String" />

                        <asp:Parameter Name="class" Type="Int32" />

                    </InsertParameters>

                    <UpdateParameters>

                        <asp:Parameter Name="name" Type="String" />

                        <asp:Parameter Name="gender" Type="String" />

                        <asp:Parameter Name="class" Type="Int32" />

                        <asp:Parameter Name="Id" Type="Int32" />

                    </UpdateParameters>


                </asp:SqlDataSource>

            </td>

            <td></td>

        </tr>

    </table>


    <%--<main>

        <section class="row" aria-labelledby="aspnetTitle">

            <h1 id="aspnetTitle">ASP.NET</h1>

            <p class="lead">ASP.NET is a free web framework for building great Web sites and Web applications using HTML, CSS, and JavaScript.</p>

            <p><a href="http://www.asp.net" class="btn btn-primary btn-md">Learn more &raquo;</a></p>

        </section>


        <div class="row">

            <section class="col-md-4" aria-labelledby="gettingStartedTitle">

                <h2 id="gettingStartedTitle">Getting started</h2>

                <p>

                    ASP.NET Web Forms lets you build dynamic websites using a familiar drag-and-drop, event-driven model.

                A design surface and hundreds of controls and components let you rapidly build sophisticated, powerful UI-driven sites with data access.

                </p>

                <p>

                    <a class="btn btn-default" href="https://go.microsoft.com/fwlink/?LinkId=301948">Learn more &raquo;</a>

                </p>

            </section>

            <section class="col-md-4" aria-labelledby="librariesTitle">

                <h2 id="librariesTitle">Get more libraries</h2>

                <p>

                    NuGet is a free Visual Studio extension that makes it easy to add, remove, and update libraries and tools in Visual Studio projects.

                </p>

                <p>

                    <a class="btn btn-default" href="https://go.microsoft.com/fwlink/?LinkId=301949">Learn more &raquo;</a>

                </p>

            </section>

            <section class="col-md-4" aria-labelledby="hostingTitle">

                <h2 id="hostingTitle">Web Hosting</h2>

                <p>

                    You can easily find a web hosting company that offers the right mix of features and price for your applications.

                </p>

                <p>

                    <a class="btn btn-default" href="https://go.microsoft.com/fwlink/?LinkId=301950">Learn more &raquo;</a>

                </p>

            </section>

        </div>

    </main>--%>


</asp:Content>

Above File is CRUD_GRIDVIEW\Default.aspx

















<?xml version="1.0" encoding="utf-8"?>
<!--
  For more information on how to configure your ASP.NET application, please visit
  https://go.microsoft.com/fwlink/?LinkId=169433
  -->
<configuration>
  <system.web>
    <compilation debug="true" targetFramework="4.7.2" />
    <httpRuntime targetFramework="4.7.2" />
    <pages>
      <namespaces>
        <add namespace="System.Web.Optimization" />
      </namespaces>
      <controls>
        <add assembly="Microsoft.AspNet.Web.Optimization.WebForms" namespace="Microsoft.AspNet.Web.Optimization.WebForms" tagPrefix="webopt" />
      </controls>
    </pages>
  </system.web>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="Antlr3.Runtime" publicKeyToken="eb42632606e9261f" />
        <bindingRedirect oldVersion="0.0.0.0-3.5.0.2" newVersion="3.5.0.2" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Microsoft.Web.Infrastructure" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="0.0.0.0-2.0.0.0" newVersion="2.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" />
        <bindingRedirect oldVersion="0.0.0.0-13.0.0.0" newVersion="13.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="WebGrease" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="0.0.0.0-1.6.5135.21930" newVersion="1.6.5135.21930" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
  <system.codedom>
    <compilers>
      <compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=2.0.1.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:default /nowarn:1659;1699;1701" />
      <compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=2.0.1.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:default /nowarn:41008 /define:_MYTYPE=\&quot;Web\&quot; /optionInfer+" />
    </compilers>
  </system.codedom>
<connectionStrings>
  <add name="dbcs" connectionString="Data Source=HEER\SQLEXPRESS;Initial Catalog=Crud_Db;Integrated Security=True;Encrypt=False"
    providerName="System.Data.SqlClient" />
  <add name="Crud_DbConnectionString" connectionString="Data Source=HEER\SQLEXPRESS;Initial Catalog=Crud_Db;Integrated Security=True;Encrypt=False"
    providerName="System.Data.SqlClient" />
  <add name="Crud_DbConnectionString2" connectionString="Data Source=HEER\SQLEXPRESS;Initial Catalog=Crud_Db;Integrated Security=True;Encrypt=False"
    providerName="System.Data.SqlClient" />
</connectionStrings>
</configuration>
Above File is CRUD_GRIDVIEW\Web.config


























Comments

Popular posts from this blog

Create a User Registration Form in ASP.NET using SQL Server, Visual Studio 2022 & Bootstrap

Create a Simple Login Form in ASP.NET using Visual Studio 2022

SqlCommand Class ADO.Net | ExecuteNonQuery | ExecuteReader | ExecuteScalar