Display Data on or Bind/Populate GridView - ASP.NET and SQL Server

 <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="aspInsertUpdateDeleteOperation.WebForm1" %>


<!DOCTYPE html>


<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

    <title></title>

    <style type="text/css">

        .auto-style1{

            width:100%;

        }

        .auto-style2 {

            width: 71px;

        }

    </style>

</head>

<body>

    <form id="form1" runat="server">

        <div>

            <table align="center" class="auto-style1">

                <tr>

                    <td class="auto-style2">ID</td>

                    <td>

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

                    </td>

                </tr>

                <tr>

                    <td class="auto-style2">Name</td>

                    <td>

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

                    </td>

                </tr>

                <tr>

                    <td class="auto-style2">Phone</td>

                    <td>

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

                    </td>

                </tr>

                <tr>

                    <td class="auto-style2">Address</td>

                    <td>

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

                    </td>

                </tr>

                <tr>

                    <td class="auto-style2">

                    </td>

                    <td>

                        <asp:Button ID="btnInsert" runat="server" Text="Insert" OnClick="btnInsert_Click"/>

                        <asp:Button ID="btnDelete" runat="server" Text="Delete" OnClick="btnDelete_Click" OnClientClick="return confirm('Are you sure to delete ?')"/>

                        <asp:Button ID="btnUpdate" runat="server" Text="Update" OnClick="btnUpdate_Click"/>

                        <asp:Button ID="btnReset" runat="server" Text="Reset" OnClick="btnReset_Click"/>

                    </td>

                </tr>

                <tr>

                    <td class="auto-style2" colspan="2">

                        <br />

                    </td>

                </tr>

                <tr>

                    <asp:GridView ID="GridView1" runat="server" BackColor="#CCCCCC" BorderColor="#999999" BorderStyle="Solid" BorderWidth="3px" CellPadding="4" CellSpacing="2" ForeColor="Black">

                        <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>

                </tr>

            </table>

        </div>

    </form>

</body>

</html>

ABOVE FILE IS WebForm1.aspx














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 aspInsertUpdateDeleteOperation
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        string cs = ConfigurationManager.ConnectionStrings["dbcs"].ConnectionString;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                ShowData();
            }
        }

        protected void EmptyControls()
        {
            txtID.Text = "";
            txtName.Text = "";
            txtPhone.Text = "";
            txtAddress.Text = "";
        }

        protected void ShowData()
        {
            try
            {
                using(SqlConnection con = new SqlConnection(cs))
                {
                    con.Open();
                    string query = "SELECT * FROM idus";
                    SqlCommand cmd = new SqlCommand(query,con);
                    SqlDataReader sdr = cmd.ExecuteReader();
                    GridView1.DataSource = sdr;
                    GridView1.DataBind();


                    //Usage of SqlDataAdpater as shown below:
                    //SqlDataAdapter sda = new SqlDataAdapter();
                    //DataTable data = new DataTable();
                    //sda.Fill(data);
                    //GridView1.DataSource = data;
                    //GridView1.DataBind();
                }
            }
            catch (SqlException ex)
            {
                Response.Write("SqlException: " + ex.Message);
            }
            catch (Exception ex)
            {
                Response.Write("Exception: " + ex.Message);
            }
        }

        protected void btnInsert_Click(object sender, EventArgs e)
        {
            try
            {
                using(SqlConnection con = new SqlConnection(cs))
                {
                    con.Open();
                    string query = "INSERT INTO idus(ID,name,phone,address) VALUES(@ID,@name,@phone,@address)";
                    SqlCommand cmd = new SqlCommand(query,con);
                    cmd.Parameters.AddWithValue("@ID",txtID.Text);
                    cmd.Parameters.AddWithValue("@name",txtName.Text);
                    cmd.Parameters.AddWithValue("@phone",txtPhone.Text);
                    cmd.Parameters.AddWithValue("@address",txtAddress.Text);
                    cmd.ExecuteNonQuery();
                    Response.Write("Data inserted successfully");
                    EmptyControls();
                }
            }
            catch (SqlException ex)
            {
                Response.Write("SqlException: " + ex.Message);
            }
            catch (Exception ex)
            {
                Response.Write("Exception: " + ex.Message);
            }
        }

        protected void btnDelete_Click(object sender, EventArgs e)
        {
            try
            {
                using(SqlConnection con = new SqlConnection(cs))
                {
                    con.Open();
                    string query = "DELETE FROM idus WHERE ID=@ID";
                    SqlCommand cmd = new SqlCommand(query,con);
                    cmd.Parameters.AddWithValue("@ID",txtID.Text);
                    cmd.ExecuteNonQuery();
                    Response.Write("Data deleted successfully");
                    EmptyControls();
                }
            }
            catch (SqlException ex)
            {
                Response.Write("SqlException: " + ex.Message);
            }
            catch (Exception ex)
            {
                Response.Write("Exception: " + ex.Message);
            }
        }

        protected void btnUpdate_Click(object sender, EventArgs e)
        {
            try
            {
                using(SqlConnection con = new SqlConnection(cs))
                {
                    con.Open();
                    string query = "UPDATE idus SET name=@name,phone=@phone,address=@address WHERE ID=@ID";
                    SqlCommand cmd = new SqlCommand(query,con);
                    cmd.Parameters.AddWithValue("@ID",txtID.Text);
                    cmd.Parameters.AddWithValue("@name",txtName.Text);
                    cmd.Parameters.AddWithValue("@phone",txtPhone.Text);
                    cmd.Parameters.AddWithValue("@address",txtAddress.Text);
                    cmd.ExecuteNonQuery();
                    Response.Write("Data updated successfully");
                    EmptyControls();
                }
            }
            catch (SqlException ex)
            {
                Response.Write("SqlException: " + ex.Message);
            }
            catch (Exception ex)
            {
                Response.Write("Exception: " + ex.Message);
            }
        }

        protected void btnReset_Click(object sender, EventArgs e)
        {
            try
            {
                EmptyControls();
            }
            catch (SqlException ex)
            {
                Response.Write("SqlException: " + ex.Message);
            }
            catch (Exception ex)
            {
                Response.Write("Exception: " + ex.Message);
            }
        }
    }
}
ABOVE FILE IS WebForm1.aspx.cs















<?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=DESKTOP-77M6N4G\SQLEXPRESS;Initial Catalog=aspiudoperation;Integrated Security=True;TrustServerCertificate=True" providerName="System.Data.SqlClient"/>
</connectionStrings>
</configuration>
ABOVE FILE IS Web.config














CREATE DATABASE aspiudoperation;

USE aspiudoperation;

CREATE TABLE idus(
ID INT NOT NULL,
name NVARCHAR(50) NOT NULL,
phone NVARCHAR(50) NOT NULL,
address NVARCHAR(50) NOT NULL
);

SELECT * FROM idus;








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