Link to home
Start Free TrialLog in
Avatar of slb2008
slb2008Flag for United States of America

asked on

Delete Record row on GridView using Ajax Modal Popup

Dear Experts,

Happy New Year 2010 :)

Please see my code below.  

Delete.Aspx :

<%@ Page Language="VB" AutoEventWireup="false" CodeFile="DELETE.aspx.vb" Inherits="DELETE" %>

<%@ 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 runat="server">
    <title></title>
    <script type="text/javascript">
   
      function pageLoad() {
      }
   
    </script>
   
   
    <style type="text/css">
    .modalBackground {
            background-color:Gray;
            filter:alpha(opacity=70);
            opacity:0.7;
        }
        .confirm{
           background-color:White;
           padding:10px;
           width:370px;
        }
    </style>
   
<script type="text/javascript">
        //  keeps track of the delete button for the row
        //  that is going to be removed
        var _source;
        // keep track of the popup div
        var _popup;
       
        function showConfirm(source){
            this._source = source;
            this._popup = $find('mdlPopup');
           
            //  find the confirm ModalPopup and show it  
            this._popup.show();
        }
       
        function okClick(){
            //  find the confirm ModalPopup and hide it  
            this._popup.hide();
            //  use the cached button as the postback source
            __doPostBack(this._source.name, '');
        }
       
        function cancelClick(){
            //  find the confirm ModalPopup and hide it
            this._popup.hide();
            //  clear the event source
            this._source = null;
            this._popup = null;
        }
    </script>


</head>
<body>
    <form id="form1" runat="server">
   
        <asp:ScriptManager ID="ScriptManager1" runat="server" />
   
   
    <asp:UpdateProgress ID="UpdateProgress1" runat="server" AssociatedUpdatePanelID="UpdatePanel1">
   
     <ProgressTemplate>
                <div id="progressBackgroundFilter">
                </div>
                <div id="processMessage">
                    Please Wait .....</div>
            </ProgressTemplate>
    </asp:UpdateProgress>
   
    <cc1:ModalPopupExtender id="md1" runat="server" backgroundcssclass="modalBackground"
            behaviorid="mdlPopup" cancelcontrolid="btnNo" okcontrolid="btnOk" oncancelscript="cancelClick();"
            onokscript="okClick();" popupcontrolid="div" targetcontrolid="div"> </cc1:modalpopupextender>
       
       
        <div id="div" runat="server" align="center" class="confirm" style="display:none;" >
        <div style="background-color :red; color:White;  width:350px; ">Confirm Delete</div><p></p>
            Are you sure you want to delete ?
            <asp:Button ID="btnOk" runat="server" Text="Yes" Width="50px" />
            <asp:Button ID="btnNo" runat="server" Text="No" Width="50px" />
        </div>

   
    <asp:UpdatePanel ID="UpdatePanel1" runat="server">
    <ContentTemplate>
   
    &nbsp;<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" CellPadding="4"
                    DataKeyNames="employeeid" DataSourceID="SqlDataSource1" ForeColor="#333333" AllowPaging="True">
                    <FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
                     <Columns>
                        <asp:BoundField DataField="FirstName" HeaderText="First Name" SortExpression="FirstName" />
                        <asp:BoundField DataField="LastName" HeaderText="Last Name" SortExpression="LastName" />
                        <asp:BoundField DataField="City" HeaderText="City" SortExpression="City" />
                        <asp:BoundField DataField="Title" HeaderText="Title" SortExpression="Title" />
                        <asp:TemplateField>
                            <ItemTemplate>
                                <asp:Button ID="Button1" runat="server" CausesValidation="False" CommandArgument='<%# Eval("EmployeeID") %>'
                                    OnClick="Button1_Click" OnClientClick="showConfirm(this); return false;" Text="Delete" />
                            </ItemTemplate>
                        </asp:TemplateField>
                    </Columns>

                    <RowStyle BackColor="#EFF3FB" />
                    <EditRowStyle BackColor="#2461BF" />
                    <SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
                    <PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
                    <HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
                    <AlternatingRowStyle BackColor="White" />
                </asp:GridView>

   
   
        <asp:SqlDataSource ID="SqlDataSource1" runat="server"
            ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString %>"
           
            SelectCommand="SELECT [Employeeid], [FirstName], [LastName], [City], [Title] FROM [Employees]">
        </asp:SqlDataSource>

   
   
   </ContentTemplate>
    </asp:UpdatePanel>
    </form>
</body>
</html>


Delete.VB:

Partial Class DELETE
    Inherits System.Web.UI.Page

    'Click Delete Button from fifth column of the GridView
    Protected Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs)
        ' get the gridviewrow from the sender so we can get the datakey we need
        Dim btnDelete As Button = TryCast(sender, Button)
        Dim row As GridViewRow = DirectCast(btnDelete.NamingContainer, GridViewRow)


    End Sub

    Protected Sub btnOk_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnOk.Click


        Dim cmd As Data.SqlClient.SqlCommand
        Dim strSQL As String
        Dim strCnn As String
        Dim cnn As Data.SqlClient.SqlConnection
        Dim dr As Data.SqlClient.SqlDataReader
        'Dim employeeID As Integer = e.Item.Cells(0).Text
        'Dim EmployeeID As Integer = Integer.Parse(btnDelete.CommandArgument)
        Dim EmployeeID As Integer

        strSQL = "DELETE FROM Employees WHERE employeeID=" & employeeID


        strCnn = System.Configuration.ConfigurationManager.AppSettings("NorthwindConnectionString")

        cnn = New Data.SqlClient.SqlConnection(strCnn)

        cmd = New Data.SqlClient.SqlCommand(strSQL, cnn)
        cnn.Open()

        dr = cmd.ExecuteReader(Data.CommandBehavior.SingleRow Or Data.CommandBehavior.CloseConnection)

        cnn.Close()

    End Sub

    Protected Sub btnNo_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnNo.Click

    End Sub
End Class


I would like to know how to delete selected record/row on GridView using ajax modal popup.  Please no links samples, just a good and quick solution.  As you can see my code, there is something is missing.  The modal popup is working well , but  after click yes nothing seems to working, doesnt
delete the selected record(row).

Your quick help is really appreciated.  
Sincerely Thanks, slb2008  
Avatar of rajeeshmca
rajeeshmca
Flag of India image

HI slb2008,

First of all i dont think, Button1_Click will be triggered.

Take off the okcontrolid="btnOk". Instead the postback will make the pop up to hide and also trigger the event.
Avatar of slb2008

ASKER

Hi rajesshmca,
Thanks for your quick response.  I am going to test it and I will let you know.
 
Avatar of slb2008

ASKER

I tested it and nothing is working.  Could you please test my code and why is not working.  I remove the okcontrolid="BtnOK".  
Hope to hear from you soon.  Thanks
 
Avatar of slb2008

ASKER

Is there someone could please help me here??????
 
Thanks.
ASKER CERTIFIED SOLUTION
Avatar of rajeeshmca
rajeeshmca
Flag of India image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of slb2008

ASKER

Hi rajeeshmca,
I tried the code and I can tell you it worked so WELL.  One more thing:  After clicked the button Yes, the modal popup closes and the gridview doesn't refresh on the record that was delete!!!!!  After deleted the record is supposed to be gone, but not... to make the delete record gone I need to use right click mouse to refresh the gridview and I don't want to do this.
How I could avoid this ?  I don't want to use response.redirect that also refresh the page and gridview, but points to the first paging of the grid view instead of staying in the record was deleted.
Hope to hear from you soon.  Thanks.
Hi slb2008,

Just bind your grid again after the deletion like

Protected Sub btnOk_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnOk.Click
        Dim cmd As Data.SqlClient.SqlCommand
        Dim strSQL As String
        Dim strCnn As String
        Dim cnn As Data.SqlClient.SqlConnection
        Dim dr As Data.SqlClient.SqlDataReader
        'Dim employeeID As Integer = e.Item.Cells(0).Text
        'Dim EmployeeID As Integer = Integer.Parse(btnDelete.CommandArgument)
        Dim EmployeeID As Integer
        EmployeeID = Convert.ToInt32(HiddenFieldValuesd.Value)
        strSQL = "DELETE FROM Employees WHERE employeeID=" & EmployeeID


        strCnn = "server=RAJEESH-FAA273F\SQLEXPRESS; database=Northwind; Integrated security = true;"

        cnn = New Data.SqlClient.SqlConnection(strCnn)

        cmd = New Data.SqlClient.SqlCommand(strSQL, cnn)
        cnn.Open()

        dr = cmd.ExecuteReader(Data.CommandBehavior.SingleRow Or Data.CommandBehavior.CloseConnection)

        cnn.Close()

        'Call the Bind function here like gridView.Datasource = sometable; gridview.DataBind()
    End Sub
Avatar of slb2008

ASKER

Hi rajeeshmca,
I put the the bind function like this:
gridview1.DataSource = employees
gridview1.DataBind()
isn't not working because name Employees is not declared.  
What do I put in the line code to declare the name table?
Thanks
 
Hi sunda2010,

just give

gridview1.DataSource = SqlDataSource1

gridview1.DataBind()
Avatar of slb2008

ASKER

I received your answer but I am not sure it was for me. But is still not working.  I don't have SqlDataSource1 in my application. Needs the declare name...
Thanks
 
hi,
the answer was for u only. U have a sqldatasource and its id is SqlDataSource1.

<asp:SqlDataSource ID="SqlDataSource1" runat="server"
            ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString %>"
           
            SelectCommand="SELECT [Employeeid], [FirstName], [LastName], [City], [Title] FROM [Employees]">
        </asp:SqlDataSource>

This is the id i have given for the gridview. the only wrong thing i have done was i gave the Datasource instead of datasourceid like

GridView1.DataSourceID = "SqlDataSource1"
GridView1.DataBind()

This will work definitely
Avatar of slb2008

ASKER

rajeeshmca,
I believe it will work, but I changed my code to be more VB programmatically.  Here is my similar code almost the same but without SQLDATASOURCE1 :
 Delete.Aspx :

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title></title>

    <script type="text/javascript">
   
      function pageLoad() {
      }
   
    </script>

    <style type="text/css">
    .modalBackground {
            background-color:Gray;
            filter:alpha(opacity=70);
            opacity:0.7;
        }
        .confirm{
           background-color:White;
           padding:10px;
           width:370px;
        }
    </style>

    <script type="text/javascript">
        //  keeps track of the delete button for the row
        //  that is going to be removed
        var _source;
        // keep track of the popup div
        var _popup;
       
        function showConfirm(source){
        var id = source.id.substring(0,source.id.lastIndexOf('_')+1);
       
        document.getElementById("HiddenFieldValuesd").value = document.getElementById(id + "EmployeeIDHF").value;
            this._source = source;
            this._popup = $find('mdlPopup');
           
            //  find the confirm ModalPopup and show it  
            this._popup.show();
        }
       
        function cancelClick(){
            //  find the confirm ModalPopup and hide it
            this._popup.hide();
            //  clear the event source
            this._source = null;
            this._popup = null;
        }
    </script>

</head>
<body>
    <form id="form1" runat="server">
        <asp:ScriptManager ID="ScriptManager1" runat="server" />
        <asp:UpdateProgress ID="UpdateProgress1" runat="server" AssociatedUpdatePanelID="UpdatePanel1">
            <ProgressTemplate>
                <div id="progressBackgroundFilter">
                </div>
                <div id="processMessage">
                    Please Wait .....</div>
            </ProgressTemplate>
        </asp:UpdateProgress>
        <cc1:modalpopupextender id="md1" runat="server" backgroundcssclass="modalBackground"
            behaviorid="mdlPopup" cancelcontrolid="btnNo" oncancelscript="cancelClick();"
             popupcontrolid="div" targetcontrolid="Button1"> </cc1:modalpopupextender>
             <asp:Button ID="Button1" runat="server" style="display:none;" />
        <div id="div" runat="server" align="center" class="confirm" style="display: none;">
            <div style="background-color: red; color: White; width: 350px;">
                Confirm Delete</div>
            <p>
            </p>
            Are you sure you want to delete ?
            <asp:Button ID="btnOk" runat="server" Text="Yes" Width="50px" />
            <asp:Button ID="btnNo" runat="server" Text="No" Width="50px" />
        </div>
        <asp:UpdatePanel ID="UpdatePanel1" runat="server">
            <ContentTemplate>
                &nbsp;
                <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" CellPadding="4"
                    DataKeyNames="employeeid"  ForeColor="#333333" AllowPaging="True">
                    <FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />

         
                    <Columns>
                        <asp:BoundField DataField="FirstName" HeaderText="First Name" SortExpression="FirstName" />
                        <asp:BoundField DataField="LastName" HeaderText="Last Name" SortExpression="LastName" />
                        <asp:BoundField DataField="City" HeaderText="City" SortExpression="City" />
                        <asp:BoundField DataField="Title" HeaderText="Title" SortExpression="Title" />
                        <asp:TemplateField>
                            <ItemTemplate>
                                <asp:Button ID="Button1" runat="server" CausesValidation="False" CommandArgument='<%# Eval("EmployeeID") %>'
                                     OnClientClick="showConfirm(this); return false;" Text="Delete" />
                                     <asp:HiddenField ID="EmployeeIDHF" runat="server" Value='<%# Eval("EmployeeID") %>' />
                            </ItemTemplate>
                        </asp:TemplateField>
                    </Columns>
                    <RowStyle BackColor="#EFF3FB" />
                    <EditRowStyle BackColor="#2461BF" />
                    <SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
                    <PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
                    <HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
                    <AlternatingRowStyle BackColor="White" />
                </asp:GridView>
                               
            </ContentTemplate>
        </asp:UpdatePanel>
        <asp:HiddenField ID="HiddenFieldValuesd" runat="server" />
    </form>
</body>
</html>


in the code behind have the following

DELETE.VB
 
 
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load, Me.Load
        'Put user code to initialize the page here
        If Not Page.IsPostBack Then
 
           
            'Fill Data in the GridView
            DataFillinGridView("Firstname")
            GridLoad()
           
 
        End If
 
 
 
Private Sub DataFillinGridView(ByVal SortExpression As String)
 
        Dim da As SqlDataAdapter
        Dim ds As DataSet
        Dim strSQL As String
        Dim strCnn As String
 
        strSQL = " SELECT [Employeeid], [FirstName], [LastName], [City], [Title] FROM [Employees] " 
 
 
        strCnn = System.Configuration.ConfigurationManager.AppSettings("NorthwindConnectionString ")
        da = New SqlDataAdapter(strSQL, strCnn)
        ds = New Data.DataSet()
        da.Fill(ds, "Employees")
        Session("DataView") = ds.Tables("Employees ").DefaultView()
 
        'Count num Companies
        Dim numRecs As Integer
        numRecs = ds.Tables("Employees ").Rows.Count()
 
        Me.lblRecCount.Text = "Employee Count: " & numRecs.ToString
        Session("DataView") = ds.Tables("Employees ").DefaultView()
        'HandleSort(SortExpression)
 
    End Sub
 
 
    Private Sub GridLoad()
 
        Dim dv As Data.DataView
 
        Me. GridView1.AutoGenerateColumns = False
        Me. GridView1.Visible = True
        Me. GridView1.Enabled = True
 
        ''fill the grid with data:
        Me. GridView1.DataSource = Session("DataView")
        Me. GridView1.DataBind()
 
        ''show the record count:
        dv = CType(Session("DataView"), Data.DataView)
 
    End Sub
 
    'call for sorting:
    Private Sub GridView1_Sorting(ByVal source As System.Object, ByVal e As System.Web.UI.WebControls.GridViewSortEventArgs)
 
        HandleSort(e.SortExpression)
        'SortExpression for each column has been set in the properties window
        GridLoad()
 
    End Sub
 
    Public Sub HandleSort(ByVal SortExpression As String)
        Dim strDir As String
        Dim dv As DataView
 
        If SortExpression = String.Empty Then
            SortExpression = "EmployeeID"
 
            strDir = "ASC"
        End If
        If SortExpression = CStr(Session("Sort")) Then
            If CStr(Session("SortDirection")) = "ASC" Then
                strDir = "ASC"
            Else
                strDir = "DESC"
            End If
        Else
            strDir = "DESC"
        End If
 
        dv = CType(Session("DataView"), DataView)
        dv.Sort = SortExpression & " " & strDir
        Session("Sort") = SortExpression
        Session("SortDirection") = strDir
 
    End Sub
 
Protected Sub GridView1_RowCreated(ByVal sender As Object, ByVal e As GridViewRowEventArgs)
        ' only apply changes if its DataRow
        If e.Row.RowType = DataControlRowType.DataRow Then
 
            ' when mouse is over the row, save original color to new attribute, and change it to highlight orange color
            e.Row.Attributes.Add("onmouseover", "this.originalstyle=this.style.backgroundColor;this.style.backgroundColor='#aab9db'")
 
            ' when mouse leaves the row, the background change the color to its original value    
            e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor=this.originalstyle;")
        End If
 
    End Sub
 
 
Protected Sub btnOk_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnOk.Click

        Dim cmd As Data.SqlClient.SqlCommand
        Dim strSQL As String
        Dim strCnn As String
        Dim cnn As Data.SqlClient.SqlConnection
        Dim dr As Data.SqlClient.SqlDataReader
               
 
        EmployeeID = Convert.ToInt32(HiddenFieldValuesd.Value)
        strSQL = "DELETE FROM Employees WHERE employeeID=" & EmployeeID


        strCnn = "server=RAJEESH-FAA273F\SQLEXPRESS; database=Northwind; Integrated security = true;"

        cnn = New Data.SqlClient.SqlConnection(strCnn)

        cmd = New Data.SqlClient.SqlCommand(strSQL, cnn)
        cnn.Open()

        dr = cmd.ExecuteReader(Data.CommandBehavior.SingleRow Or Data.CommandBehavior.CloseConnection)

        cnn.Close()
 
 
What could be here?
 
GridView1.DataSource = ???????   ---- needs declare
GridView1.DataBind ()
UpdatePanel1.Update() ????
 

    End Sub
 Thanks
This is enough

DataFillinGridView("Firstname")
GridLoad()
Avatar of slb2008

ASKER

rajeeshmca,
First of all I would like to tell it's working really well.  Thanks for your patience and help.  This was a good solution and you are going to receive 500 points.
Sincerely thanks, slb2008.
 
 
Avatar of slb2008

ASKER

rajeeshmca  did a great job to help me with a good  and quick solution I was looking for awhile.