Wednesday 13 March 2013

How to Insert,Update,Delete record in Modal Popup Window in asp.net


Description:-

in this Example we explain that how to Insert,Update,Delete Recored in Ajax Modal popup means Perform the CRUD operation in Modal popup.
The ModalPopup extender allows a page to display content to the user in a "modal" manner which prevents the user from interacting with the rest of the page. The Modal popup is Display like HighLighting the Image and only Focus on it.The modal content can be any  controls and is displayed above a background that can have a custom style applied to it. 

When Modal popup is displayed, only the content of the modal  can be interacted with; clicking on the rest of the page does nothing. When the user is done interacting with the modal content, a click of an OK/Cancel control dismisses the modal content and optionally runs custom script. The custom script will typically be used to apply whatever changes were made while the modal mode was active. If a postback is required, simply allow the OK/Cancel control to postback and the page to re-render. You can also absolutely position a modal popup by setting the X and Y properties. By default it is centered on the page, however if just X or Y is specified then it is centered vertically or horizontally.


Property of the ModalPopupExtender:-

·  TargetControlID - The ID of the  activates the modal popup.

·  PopupControlID - The ID of the element to display as a modal popup like Button etc….

·  BackgroundCssClass - The CSS class for Popup to apply to the background when the modal popup is displayed.

·  DropShadow - True to automatically add a dropshadow to the modal popup.

·  OkControlID - The ID of the element that dismisses the modal popup.

·  OnOkScript - The script to run when the modal popup is dismissed using the element specified in OkControlID.

·  CancelControlID - The ID of the Control that cancels the modal popup

·  OnCancelScript - Script to run when the modal popup is dismissed with the CancelControlID

·  PopupDragHandleControlID - The ID of the embedded element that contains the popup header/title which will be used as a drag handle

·  X - The X coordinate of the top/left corner of the modal popup (the popup will be centered horizontally if not specified)
·  Y - The Y coordinate of the top/left corner of the modal popup (the popup will be centered vertically if not specified)

·  RepositionMode - The setting that determines if the popup needs to be repositioned when the window is resized or scrolled.


to show Example of insert,update,delete in gridview using WCF Service please click here WCF Service For Insert,update,Delete
             
to show Example of insert,update,delete in gridview using LINQ please click here insert,update,delete using Linq

to show Example of insert,update,delete in gridview using Naming Container please click here Naming Container for insert update Delete in Gridview

to show Example of insert,update,delete in gridview using Modal Popup please click here insert,update,delete in Modal Popup

 to show Example of insert,update,delete in gridview using Stored Procedure please click here insert,update,delete through stored Procedure

  to show Example of insert,update,delete in XML File and bind to Gridview please click here insert,upadte,delete in XML File

  to show Example of insert,update,delete in gridview using Three Tier Architecture please click here Three Tier Architecture For insert,update,Delete

To show example of MVC ModalPopup for insert,update,delete Record in mvc using popup please click here modalpopup in MVC with insert,update,delete record

To Show Example of Insert,Update,Delete then click Here  CRUD operation in Reapetor control

addproduct.aspx:-

<%@ Page Title="" Language="C#" MasterPageFile="~/MasterPage2.master" AutoEventWireup="true" CodeFile="addproduct.aspx.cs" Inherits="addproduct" %>
<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
<link rel="stylesheet" type="text/css" href="styles.css">
<script type="text/javascript">
    function search1(str) {

        if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
            xmlhttp = new XMLHttpRequest();
        }
        else {// code for IE6, IE5
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        }
        xmlhttp.onreadystatechange = function () {
            if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                document.getElementById("grid1").style.display = 'none';
                document.getElementById("grid").innerHTML = xmlhttp.responseText;
            }
        }
        xmlhttp.open("GET", "Default.aspx?q=" + str, true);
        xmlhttp.send();

    }
</script>
<style type="text/css">
.pos
{
    position:absolute;
    left:200px;
    top:175px;
    background:url('white.png');
  
}
.pos1
{
    position:absolute;
    left:200px;
    top:200px;
  
  
}
.pa
{
     position:absolute;
    left:200px;
    top:175px;
}


</style>

</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
<asp:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server">
    </asp:ToolkitScriptManager>

              
               <asp:Panel ID="panel1" runat="server"
    
        Visible="False" CssClass="pos" BackImageUrl="~/white.png" >
      
<div style="position:absolute; width:500px; left:200px; height:30px; top:175px; background-color:#00FFFF"><b style="font-size: large; font-weight: bold; color: #FFFF00; ">Add Record</b>
            
       
                   </div>
<div style="position:absolute; left:670px; top:175px">
    <asp:ImageButton ID="ImageButton1" runat="server"
        ImageUrl="~/x.png" CausesValidation="False"
        onclick="ImageButton1_Click" /></div>
<div style="background-position: url('white.png'); width:500px; height:350px; overflow:scroll; background:url('white.png')background-color:White; position:absolute; left:200px; top:200px; z-index: 3200;">
  <center>
  
  <label> <asp:Label ID="lblid" runat="server">id</asp:Label></label>
  
     <asp:TextBox ID="txtid" runat="server" CssClass="txtfield1" Visible="false"></asp:TextBox>


    <label for="password">product_image</label>
  
      <asp:FileUpload ID="Fileupload1" runat="server" CssClass="txtfield1" />



 




        <label for="email">name</label>
        <asp:TextBox ID="txtname" runat="server"  CssClass="txtfield1"></asp:TextBox>

    <asp:RequiredFieldValidator

             ID="RequiredFieldValidator8" runat="server"

             ControlToValidate="txtname"

             ErrorMessage="Address can't be left blank" Display="Dynamic"

            ></asp:RequiredFieldValidator>
           <label for="email">prize</label>
        <asp:TextBox ID="txtprize" runat="server"  CssClass="txtfield1"></asp:TextBox>

    <asp:RequiredFieldValidator

             ID="RequiredFieldValidator1" runat="server"

             ControlToValidate="txtprize"

             ErrorMessage="prze can't be left blank" Display="Dynamic"

            ></asp:RequiredFieldValidator>
    
       
            <label for="email">quantity</label>
        <asp:TextBox ID="txtqt" runat="server"  CssClass="txtfield1"></asp:TextBox>

    <asp:RequiredFieldValidator

             ID="RequiredFieldValidator2" runat="server"

             ControlToValidate="txtqt"

             ErrorMessage="quantity can't be left blank" Display="Dynamic"

            ></asp:RequiredFieldValidator>
   
       
<asp:Button ID="btnlogin" runat="server" Text="Add"
                onclick="btnlogin_Click" CssClass="btn"   />
    
       <asp:Button ID="btnupdate" runat="server" Text="Update"
                onclick="btnupdate_Click" CssClass="btn"   />
<asp:Button ID="btncancel" runat="server" Text="Cancel"
                onclick="btncancel_Click" CssClass="btn" CausesValidation="false" />
   
          </center>
  </div>
</asp:Panel>

<asp:ModalPopupExtender ID="modalPopUpExtender1"

                         runat="server"
                         
                         TargetControlID="LinkButton1"

                         PopupControlID="panel1" X="5" Y="5">

</asp:ModalPopupExtender>
<asp:ModalPopupExtender ID="modalPopUpExtender2"

                         runat="server"
                         
                         TargetControlID="btnShowPopup"

                         PopupControlID="panel1" X="5" Y="5">

</asp:ModalPopupExtender>
      <div style="position: absolute; left: 300px; top: 350px; width: 118px;">        
             
<asp:LinkButton ID="LinkButton1" runat="server" onclick="LinkButton1_Click" ><b style="font-size: large; font-weight: bold; color: #FFFF00; ">Add Record</b></asp:LinkButton>
  </div>
  <div style="position: absolute; left: 470px; top: 335px; width: 700px;">        
<b style="font-size: large; color: #FFFF00">Enter Name to Search:</b>             
<input type="text" onkeyup="search1(this.value)" class="txtfield1" value="" />
  </div>

<div id="grid" style=" width:600px; position:absolute; left:300px; top:385px;"></div>
 <div id="grid1"  style=" width:600px; position:absolute; left:300px; top:385px;">
     <asp:GridView ID="GridView1" runat="server"
   
      
     
        AutoGenerateColumns="False" DataKeyNames="id" Font-Size="Large"
        ForeColor="#333333" ShowFooter="True" CellPadding="4" GridLines="None"
            PageSize="10" AllowPaging="True" onrowdeleting="GridView1_RowDeleting"
            >
        <FooterStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
        <RowStyle BackColor="#FFFBD6" ForeColor="#333333" />
        <SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="Navy" />
        <PagerStyle BackColor="#FFCC66" ForeColor="#333333" HorizontalAlign="Center" />
        <HeaderStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
        <AlternatingRowStyle BackColor="White" />
        <Columns>
            <asp:BoundField DataField="id" HeaderText="ID"/>
            <asp:TemplateField HeaderText="Image">
            <ItemTemplate>
            <asp:Image ID="i1" runat="server" ImageUrl=' <%# Eval("pr_image")%>' Height="50" Width="70" />
            <asp:Label ID="Label1" runat="server" Text=' <%# Eval("pr_image")%>' Visible="false"></asp:Label>
            </ItemTemplate>
            </asp:TemplateField>
            <asp:BoundField DataField="pr_name" HeaderText="Name" />
            <asp:BoundField DataField="prize" HeaderText="Prize"/>
            <asp:BoundField DataField="quantity" HeaderText="Quantity"/>
          
           <asp:TemplateField HeaderText="Edit">
   <ItemTemplate>
       <asp:ImageButton ID="imgbtn" ImageUrl="~/ed.jpeg" runat="server" Width="25" Height="25" onclick="imgbtn_Click" />

   </ItemTemplate>


</asp:TemplateField>
 <asp:TemplateField HeaderText="Delete">
   <ItemTemplate>
       <asp:ImageButton ID="imgbtn1" ImageUrl="~/delete.png" runat="server" Width="25" Height="25" OnClientClick="return confirm('are you sure to Delete Record ?');" CommandName="Delete" />

   </ItemTemplate>


</asp:TemplateField>

                    </Columns>
    </asp:GridView>
    </div>

 <asp:Button ID="btnShowPopup" runat="server" style="display:none" />
  



</asp:Content>



addproduct.aspx.cs

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.Web.UI.HtmlControls;
using System.IO;


public partial class addproduct : System.Web.UI.Page
{
    string add;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Session["login"] == null)
        {
            Response.Redirect("home1.aspx");
        }
        if (Request.QueryString["a"] != null)
        {
            add = Request.QueryString["g"].ToString();
            //fetchstate();
            // DropDownList1.SelectedIndex = 0;
            // city();
            if (!Page.IsPostBack)
            {

                rn();
            }

        }
        if (!Page.IsPostBack)
        {





            grid();



        }
    }
    public void rn()
    {
        panel1.Visible = true;
        modalPopUpExtender2.Show();
        // modalPopUpExtender1.Focus();
        panel1.Style.Add("background-position", "url('white.png')");
        panel1.Style.Add("opacity", "2.0");
        panel1.Style.Add("filter", "alpha(opacity=200)");

        btncancel.Visible = true;
        btnupdate.Visible = true;
        btnlogin.Visible = false;
        lblid.Visible = true;
        txtid.Visible = true;
        txtid.Text = Request.QueryString["a"].ToString();
        txtname.Text = Request.QueryString["b"].ToString();

    }




    protected void btnlogin_Click(object sender, EventArgs e)
    {
        string con = @"Data Source=SQLDB;Initial Catalog=Demo;User ID=Demod;Password=Demo1@";
        if (Fileupload1.HasFile)
        {
            string fileExtension = Path.GetExtension(Fileupload1.FileName.ToString());
            fileExtension.ToLower();
            if (fileExtension != ".gif" && fileExtension != ".jpg" && fileExtension != ".jpeg" && fileExtension != ".png")
            {
                ClientScript.RegisterClientScriptBlock(this.GetType(), "ke", "<script>alert('only jpeg,jpg,png,gif photo is allowed');</script>");
                return;
            }
            string serverPath = Server.MapPath(@"~/image/" + Fileupload1.FileName);
            Fileupload1.SaveAs(serverPath);
        }
        else
        {
            ClientScript.RegisterClientScriptBlock(this.GetType(), "ke", "<script>alert('plz browse the image');</script>");
            panel1.Visible = true;
            modalPopUpExtender1.Show();
            Fileupload1.Focus();
            return;

        }


        string q1 = "insert into k_product(pr_image,pr_name,prize,quantity,cid) values('" + "image/" + Fileupload1.FileName + "','" + txtname.Text + "','" + txtprize.Text + "','" + txtqt.Text + "','" + Session["login"].ToString() + "')";

        SqlConnection cn = new SqlConnection(con);

        SqlCommand cmd = new SqlCommand(q1, cn);

        cn.Open();

        int i = cmd.ExecuteNonQuery();
        if (i > 0)
        {
            ClientScript.RegisterClientScriptBlock(this.GetType(), "key", "<script> alert('1 record added successfully');</script>");


            grid();

        }
        cn.Close();

        panel1.Visible = false;
        modalPopUpExtender1.Hide();


        GridView1.Style.Add("background-color", "white");
        GridView1.Style.Add("opacity", "1.0");
        GridView1.Style.Add("filter", "alpha(opacity=100)");



        HtmlContainerControl f;

        f = (HtmlContainerControl)Master.FindControl("main");

        // HtmlForm f = (HtmlForm)Master.FindControl("Form2");
        f.Style.Add("background-color", "#005b7f");
        f.Style.Add("opacity", "1.0");
        f.Style.Add("filter", "alpha(opacity=100)");



    }

    protected void grid()
    {
        string con = @"Data Source=SQLDB;Initial Catalog=Demo;User ID=Demod;Password=Demo1@";
        //Menu inm = (Menu)this.Master.FindControl("Menu1");


        string q1 = "select id,pr_image,pr_name,quantity,prize from k_product where cid ='" + Session["login"].ToString() + "'";

        DataSet ds = new DataSet();
        SqlDataAdapter da = new SqlDataAdapter();
        SqlConnection cn = new SqlConnection(con);

        SqlCommand cmd = new SqlCommand(q1, cn);

        cn.Open();
        da.SelectCommand = cmd;
        cmd.ExecuteNonQuery();
        da.Fill(ds);
        GridView1.DataSource = ds;
        GridView1.DataBind();
        cn.Close();

    }




    protected void LinkButton1_Click(object sender, EventArgs e)
    {

        btncancel.Visible = false;
        btnupdate.Visible = false;
        lblid.Visible = false;
        txtid.Visible = false;
        Session["BgColor"] = "black";
        HtmlContainerControl f1;

        f1 = (HtmlContainerControl)Master.FindControl("main");

        f1.Style.Add("background-color", Session["BgColor"].ToString());



        f1.Style.Add("opacity", "0.1");
        f1.Style.Add("filter", "alpha(opacity=10)");


        GridView1.Style.Add("background-color", "black");
        GridView1.Style.Add("opacity", "0.4");
        GridView1.Style.Add("filter", "alpha(opacity=40)");



        panel1.Visible = true;
        modalPopUpExtender1.Show();

        // modalPopUpExtender1.Focus();
        panel1.Style.Add("background-position", "url('white.png')");
        panel1.Style.Add("opacity", "2.0");
        panel1.Style.Add("filter", "alpha(opacity=200)");
        txtname.Text = "";
        txtprize.Text = "";
        txtqt.Text = "";

        btnlogin.Visible = true;



    }
    protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
    {

        panel1.Visible = false;
        modalPopUpExtender1.Hide();


        GridView1.Style.Add("background-color", "white");
        GridView1.Style.Add("opacity", "1.0");
        GridView1.Style.Add("filter", "alpha(opacity=100)");


        HtmlContainerControl f;

        f = (HtmlContainerControl)Master.FindControl("main");



        f.Style.Add("background-color", "#005b7f");
        f.Style.Add("opacity", "1.0");
        f.Style.Add("filter", "alpha(opacity=100)");



    }
    protected void ImageButton2_Click(object sender, ImageClickEventArgs e)
    {

        panel1.Visible = false;
        modalPopUpExtender2.Hide();


        GridView1.Style.Add("background-color", "white");
        GridView1.Style.Add("opacity", "1.0");
        GridView1.Style.Add("filter", "alpha(opacity=100)");


        HtmlContainerControl f;

        f = (HtmlContainerControl)Master.FindControl("main");



        f.Style.Add("background-color", "#005b7f");
        f.Style.Add("opacity", "1.0");
        f.Style.Add("filter", "alpha(opacity=100)");



    }


    protected void btnupdate_Click(object sender, EventArgs e)
    {
        string con = @"Data Source=SQLDB;Initial Catalog=Demo;User ID=Demod;Password=Demo1@";

        string fileExtension = Path.GetExtension(Fileupload1.FileName.ToString());
        fileExtension.ToLower();
        if (Fileupload1.HasFile)
        {
            if (fileExtension != ".gif" && fileExtension != ".jpg" && fileExtension != ".jpeg" && fileExtension != ".png")
            {
                ClientScript.RegisterClientScriptBlock(this.GetType(), "ke", "<script>alert('only jpeg,jpg,png,gif photo is allowed');</script>");
                return;
            }
            string serverPath = Server.MapPath(@"~/image/" + Fileupload1.FileName);
            Fileupload1.SaveAs(serverPath);
        }
        string q1;
        if (Fileupload1.HasFile)
        {

            q1 = "update k_product set pr_image='" + "image/" + Fileupload1.FileName + "',pr_name='" + txtname.Text + "',prize='" + txtprize.Text + "',quantity='" + txtqt.Text + "' where id ='" + txtid.Text + "'";

        }
        else
        {

            q1 = "update k_product set pr_image='" + btnShowPopup.Text + "',pr_name='" + txtname.Text + "',prize='" + txtprize.Text + "',quantity='" + txtqt.Text + "' where id ='" + txtid.Text + "'";
        }

        SqlConnection cn = new SqlConnection(con);

        SqlCommand cmd = new SqlCommand(q1, cn);

        cn.Open();

        int i = cmd.ExecuteNonQuery();
        if (i > 0)
        {
            ClientScript.RegisterClientScriptBlock(this.GetType(), "key", "<script> alert('1 record updated successfully');</script>");


            grid();

        }
        cn.Close();
        panel1.Visible = false;
        modalPopUpExtender2.Hide();




        GridView1.Style.Add("background-color", "white");
        GridView1.Style.Add("opacity", "1.0");
        GridView1.Style.Add("filter", "alpha(opacity=100)");



        HtmlContainerControl f;

        f = (HtmlContainerControl)Master.FindControl("main");


        f.Style.Add("background-color", "#005b7f");
        f.Style.Add("opacity", "1.0");
        f.Style.Add("filter", "alpha(opacity=100)");


    }
    protected void btncancel_Click(object sender, EventArgs e)
    {

        panel1.Visible = false;
        modalPopUpExtender2.Hide();


        GridView1.Style.Add("background-color", "white");
        GridView1.Style.Add("opacity", "1.0");
        GridView1.Style.Add("filter", "alpha(opacity=100)");



        HtmlContainerControl f;

        f = (HtmlContainerControl)Master.FindControl("main");
        f.Style.Add("background-color", "#005b7f");
        f.Style.Add("opacity", "1.0");
        f.Style.Add("filter", "alpha(opacity=100)");


    }
    protected void imgbtn_Click(object sender, ImageClickEventArgs e)
    {
        Session["BgColor"] = "black";

        HtmlContainerControl f1;

        f1 = (HtmlContainerControl)Master.FindControl("main");
        f1.Style.Add("background-color", Session["BgColor"].ToString());

        f1.Style.Add("opacity", "0.1");
        f1.Style.Add("filter", "alpha(opacity=10)");

        GridView1.Style.Add("background-color", "black");
        GridView1.Style.Add("opacity", "0.4");
        GridView1.Style.Add("filter", "alpha(opacity=40)");


        panel1.Visible = true;
        modalPopUpExtender2.Show();
        // modalPopUpExtender1.Focus();
        panel1.Style.Add("background-position", "url('white.png')");
        panel1.Style.Add("opacity", "2.0");
        panel1.Style.Add("filter", "alpha(opacity=200)");

        ImageButton btndetails = sender as ImageButton;
        GridViewRow row = (GridViewRow)btndetails.NamingContainer;
        btncancel.Visible = true;
        btnupdate.Visible = true;
        btnlogin.Visible = false;
        lblid.Visible = true;
        txtid.Visible = true;
        txtid.Text = row.Cells[0].Text;
        Label l = (Label)GridView1.Rows[row.RowIndex].Cells[1].FindControl("Label1");
        btnShowPopup.Text = l.Text;
        txtname.Text = row.Cells[2].Text;
        txtprize.Text = row.Cells[3].Text;
        txtqt.Text = row.Cells[4].Text;
        txtid.ReadOnly = true;

    }


    protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        string con = @"Data Source=SQLDB;Initial Catalog=Demo;User ID=Demod;Password=Demo1@";


        string id = GridView1.DataKeys[e.RowIndex].Value.ToString();


        string q1 = "delete from k_product where id ='" + id + "'";


        SqlConnection cn = new SqlConnection(con);

        SqlCommand cmd = new SqlCommand(q1, cn);

        cn.Open();

        int i = cmd.ExecuteNonQuery();
        if (i > 0)
        {
            ClientScript.RegisterClientScriptBlock(this.GetType(), "key", "<script> alert('1 record deleted successfully');</script>");


            grid();

        }
        cn.Close();

    }
    protected void txtsearch_TextChanged(object sender, EventArgs e)
    {

    }


}

0 comments:

Post a Comment