Thursday 5 January 2017

Insert Update Delete with Popup Window using Ado .net

Designing File
------------------------------
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="CRUD.aspx.cs" Inherits="CRUD.CRUD" %>

<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="cc1" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>GridView Add, Edit, Delete AJAX Way</title>
    <link href="CSS/CSS.css" rel="stylesheet" type="text/css" />
    <script src="scripts/jquery-1.3.2.min.js" type="text/javascript"></script>
    <script src="scripts/jquery.blockUI.js" type="text/javascript"></script>
    <script type="text/javascript">
        function BlockUI(elementID) {
            var prm = Sys.WebForms.PageRequestManager.getInstance();
            prm.add_beginRequest(function () {
                $("#" + elementID).block({
                    message: '<table align = "center"><tr><td>' +
             '<img src="images/loadingAnim.gif"/></td></tr></table>',
                    css: {},
                    overlayCSS: {
                        backgroundColor: '#000000', opacity: 0.6
                    }
                });
            });
            prm.add_endRequest(function () {
                $("#" + elementID).unblock();
            });
        }
        $(document).ready(function () {

            BlockUI("<%=pnlAddEdit.ClientID %>");
            $.blockUI.defaults.css = {};
        });
            function Hidepopup() {
                $find("popup").hide();
                return false;
            }
    </script>
    <script type="text/javascript">
        function isNumber(evt) {
            evt = (evt) ? evt : window.event;
            var charCode = (evt.which) ? evt.which : evt.keyCode;
            if (charCode > 31 && (charCode < 48 || charCode > 57)) {
                return false;
            }
            return true;
        }
    </script>
</head>
<body style="margin: 0; padding: 0">
    <form id="form1" runat="server">
        <asp:ScriptManager ID="ScriptManager1" runat="server">
        </asp:ScriptManager>
        <asp:UpdatePanel ID="UpdatePanel1" runat="server">
            <ContentTemplate>
                <asp:HiddenField ID="HdnId" runat="server" />
                <asp:Button ID="btnAdd" runat="server" Text="Add" OnClick="Add" />
                <asp:LinkButton ID="lnkFake" runat="server"></asp:LinkButton>
                <div id="Show" runat="server">
                    <asp:GridView ID="GridView1" runat="server" Width="1253px"
                        AutoGenerateColumns="False" AlternatingRowStyle-BackColor="#C2D69B"
                        HeaderStyle-BackColor="green" AllowPaging="True"
                        OnPageIndexChanging="OnPaging" CellPadding="4" ForeColor="#333333" GridLines="None">
                        <Columns>
                            <asp:BoundField DataField="firstname" HeaderText="First Name" HtmlEncode="true" />
                            <asp:BoundField DataField="lastname" HeaderText="Last Name" HtmlEncode="true" />
                            <asp:BoundField DataField="contact" HeaderText="Contact No" HtmlEncode="true" />
                            <asp:TemplateField ItemStyle-Width="30px">
                                <ItemTemplate>
                                    <asp:LinkButton ID="lnkEdit" runat="server" Text="Edit" OnClick="Edit"></asp:LinkButton>
                                    <asp:LinkButton ID="LnkDelete" runat="server" Text="Delete" OnClick="LnkDelete_Click"></asp:LinkButton>
                                    <asp:Label ID="LblId" runat="server" Text='<%# Eval("employeeid") %>' Visible="false" />
                                </ItemTemplate>
                                <ItemStyle Width="30px" />
                            </asp:TemplateField>
                        </Columns>
                        <AlternatingRowStyle BackColor="White" />
                        <EditRowStyle BackColor="#2461BF" />
                        <FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
                        <HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
                        <PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
                        <RowStyle BackColor="#EFF3FB" />
                        <SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
                        <SortedAscendingCellStyle BackColor="#F5F7FB" />
                        <SortedAscendingHeaderStyle BackColor="#6D95E1" />
                        <SortedDescendingCellStyle BackColor="#E9EBEF" />
                        <SortedDescendingHeaderStyle BackColor="#4870BE" />
                    </asp:GridView>
                </div>
                <div id="Hide" runat="server" style="margin-left:200px">
                    <asp:Label ID="Lbnljasj" runat="server" Text=".....No records found....." />
                </div>
                <asp:Panel ID="pnlAddEdit" runat="server" CssClass="modalPopup" Style="display: none">
                    <asp:Label Font-Bold="true" ID="Label4" runat="server" Text="Employee Details"></asp:Label>
                    <br />
                    <table align="center">
                        <tr>
                            <td>
                                <asp:Label ID="Label1" runat="server" Text="First Name"></asp:Label>
                            </td>
                            <td>
                                <asp:TextBox ID="TxtFirstName" MaxLength="20" runat="server"></asp:TextBox>
                                <asp:RequiredFieldValidator ID="ReQ1" runat="server" ControlToValidate="TxtFirstName" ErrorMessage="*" Display="Dynamic" ValidationGroup="Employee" />
                            </td>
                        </tr>
                        <tr>
                            <td>
                                <asp:Label ID="Label2" runat="server" Text="Last Name"></asp:Label>
                            </td>
                            <td>
                                <asp:TextBox ID="TxtLastName" runat="server" MaxLength="15"></asp:TextBox>
                                 <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="TxtLastName" ErrorMessage="*" Display="Dynamic" ValidationGroup="Employee" />
                            </td>
                        </tr>
                        <tr>
                            <td>
                                <asp:Label ID="Label3" runat="server" Text="Contact no"></asp:Label>
                            </td>
                            <td>
                                <asp:TextBox ID="TxtContactNo" runat="server" MaxLength="10" onkeypress="return isNumber(event)"></asp:TextBox>
                                 <asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ControlToValidate="TxtContactNo" ErrorMessage="*" Display="Dynamic" ValidationGroup="Employee" />
                            </td>
                        </tr>
                        <tr>
                            <td>
                                <asp:Button ID="btnSave" runat="server" Text="Save" OnClick="Save" ValidationGroup="Employee"/>
                            </td>
                            <td>
                                <asp:Button ID="btnCancel" runat="server" Text="Cancel" OnClientClick="return Hidepopup()" />
                            </td>
                        </tr>
                    </table>
                </asp:Panel>
                <cc1:ModalPopupExtender ID="popup" runat="server" DropShadow="false"
                    PopupControlID="pnlAddEdit" TargetControlID="lnkFake"
                    BackgroundCssClass="modalBackground">
                </cc1:ModalPopupExtender>
            </ContentTemplate>
            <Triggers>
                <asp:AsyncPostBackTrigger ControlID="GridView1" />
                <asp:AsyncPostBackTrigger ControlID="btnSave" />
            </Triggers>
        </asp:UpdatePanel>
    </form>
</body>
</html>
=============================================
C# Code
==========================
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace CRUD
{
    public partial class CRUD : System.Web.UI.Page
    {
        string strConnString = ConfigurationManager.ConnectionStrings["DemoConnectionString"].ConnectionString;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                BindData();
            }
        }

        private void BindData()
        {
            string strQuery = "select employeeid,firstname,lastname,contact" +
                               " from Employee";
            SqlCommand cmd = new SqlCommand(strQuery);
            DataTable dt1 = GetData(cmd);
            if (dt1.Rows.Count > 0)
            {
                Show.Visible = true;
                Hide.Visible = false;
                GridView1.DataSource = GetData(cmd);
                GridView1.DataBind();
            }
            else
            {
                Show.Visible = false;
                Hide.Visible = true;
            }
        }

        private DataTable GetData(SqlCommand cmd)
        {
            DataTable dt = new DataTable();
            using (SqlConnection con = new SqlConnection(strConnString))
            {
                using (SqlDataAdapter sda = new SqlDataAdapter())
                {
                    cmd.Connection = con;
                    con.Open();
                    sda.SelectCommand = cmd;
                    sda.Fill(dt);
                    return dt;
                }
            }
        }

        protected void OnPaging(object sender, GridViewPageEventArgs e)
        {
            this.BindData();
            GridView1.PageIndex = e.NewPageIndex;
            GridView1.DataBind();
        }

        protected void Edit(object sender, EventArgs e)
        {
            using (GridViewRow row = (GridViewRow)((LinkButton)sender).Parent.Parent)
            {
                TxtFirstName.Text = row.Cells[0].Text;
                TxtLastName.Text = row.Cells[1].Text;
                TxtContactNo.Text = row.Cells[2].Text;
                Label id=(Label)row.FindControl("LblId");
                HdnId.Value = id.Text;
                popup.Show();
            }
        }

        protected void Add(object sender, EventArgs e)
        {
            TxtFirstName.Text = string.Empty;
            TxtLastName.Text = string.Empty;
            TxtContactNo.Text = string.Empty;
            HdnId.Value = "";
            popup.Show();
        }

        protected void Save(object sender, EventArgs e)
        {
            if (HdnId.Value == "")
            {
                string query = "INSERT INTO Employee (firstname, lastname, contact) VALUES ('" + TxtFirstName.Text + "', '" + TxtLastName.Text + "', " + TxtContactNo.Text + " )";
                SqlConnection con = new SqlConnection(strConnString);
                con.Open();
                SqlCommand cmd = new SqlCommand(query, con);
                cmd.ExecuteNonQuery();
            }
            else
            {
                string ty = "UPDATE Employee SET firstname='" + TxtFirstName.Text + "',lastname='" + TxtLastName.Text + "',contact=" + TxtContactNo.Text + " WHERE employeeid=" + HdnId.Value + "";
                SqlConnection con = new SqlConnection(strConnString);
                con.Open();
                SqlCommand cmd = new SqlCommand(ty, con);
                cmd.ExecuteNonQuery();
                HdnId.Value = "";
            }
            BindData();
        }
        protected void LnkDelete_Click(object sender, EventArgs e)
        {
            using (GridViewRow row = (GridViewRow)((LinkButton)sender).Parent.Parent)
            {
                Label id = (Label)row.FindControl("LblId");
                string ty = "DELETE FROM Employee WHERE employeeid=" + id.Text + "";
                SqlConnection con = new SqlConnection(strConnString);
                con.Open();
                SqlCommand cmd = new SqlCommand(ty, con);
                cmd.ExecuteNonQuery();
            }
            BindData();
        }
    }
}

==========================


===========================================
Table Design
=======================================



vjj



No comments:

Post a Comment