Thursday, October 13, 2011

AJAX - ModalPopUpExtender in GridView

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 content can be any hierarchy of controls and is displayed above a background that can have a custom style applied to it. 


In this Article i will show you how to use AJAX ModelPopupExtender in GridView to display parent child data.


Step 1
Download Northwind database from the following link.
http://www.microsoft.com/downloads/details.aspx?FamilyID=06616212-0356-46a0-8da2-eebc53a68034&displaylang=en


Step 2
Attach a Northwind database into MS-SQL server.


Step 3
Create a Web application and give the solution name as SolModelPopUpExtenderInGridView.



Step 4
Add a ToolkitScriptManager control from Ajax toolkit inside the Div Tag,it is look like this
<asp:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server">
</asp:ToolkitScriptManager>

This control allows you to replace the default <asp:scriptmanager> control behavior, and supports the ability to dynamically merge multiple client-side Javascript scripts into a single file that is downloaded to the client at runtime. 


Step 5
Drag and place an Update Panel on the page.we will put GridView and Modal PopUp inside it. 
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
            
         <ContentTemplate>  
         </ContentTemplate>

</asp:UpdatePanel>




Step 6
Create a CSS for Modal PopUp Extender and Panel,it is look like this



Step 7
Now drag and drop GridView inside content template of Update Panel,in this example i have used Employee table of Northwind Database, it is look like this
<asp:GridView ID="GvEmployee" runat="server" AutoGenerateColumns="False" 
                                BackColor="White" BorderColor="#999999" BorderStyle="Solid" BorderWidth="1px" 
                                CellPadding="3" EnableModelValidation="True" ForeColor="Black" 
                                GridLines="Vertical">
                                <AlternatingRowStyle BackColor="#CCCCCC" />
                                <Columns>
                                    <asp:TemplateField>
                                        <ItemTemplate>
                                            <asp:LinkButton ID="btnLinkView" runat="server" onclick="btnLinkView_Click">View</asp:LinkButton>
                                        </ItemTemplate>
                                    </asp:TemplateField>
                                    <asp:BoundField DataField="FirstName" HeaderText="FirstName" />
                                    <asp:BoundField DataField="LastName" HeaderText="LastName" />
                                    <asp:BoundField DataField="BirthDate" HeaderText="BirthDate" />
                                    <asp:BoundField DataField="City" HeaderText="City" />
                                </Columns>
                                <FooterStyle BackColor="#CCCCCC" />
                                <HeaderStyle BackColor="Black" Font-Bold="True" ForeColor="White" />
                                <PagerStyle BackColor="#999999" ForeColor="Black" HorizontalAlign="Center" />
                                <SelectedRowStyle BackColor="#000099" Font-Bold="True" ForeColor="White" />
                            </asp:GridView>



Click on Image for better view


Step 8
Now add a panel with controls to display details,it is look like this

<asp:Panel ID="PnlEmployee" runat="server" CssClass="ModalPopup" style="display:none">
                                    
                                    <table border="1" cellpadding="5" cellspacing="5" width="100%" align="center" style="border-color: #FF6600">
                                            <tr>
                                                <td>First Name</td>
                                                <td><asp:Label ID="lblFirstName" runat="server"></asp:Label></td>
                                            </tr>
                                             <tr>
                                                <td>Last Name</td>
                                                <td><asp:Label ID="lblLastName" runat="server"></asp:Label></td>
                                            </tr>
                                            <tr>
                                                <td>BirthDate</td>
                                                <td><asp:Label ID="lblBirthDate" runat="server"></asp:Label></td>
                                            </tr>
                                            <tr>
                                                <td>City</td>
                                                <td><asp:Label ID="lblCity" runat="server"></asp:Label></td>
                                            </tr>
                                            <tr align="center" valign="middle">
                                                <td colspan="2">
                                                    <asp:Button ID="btnClose" runat="server" Text="Close" />
                                                </td>
                                            </tr>

                                    </table>
                                                                    
                            </asp:Panel>



Click on Image for better view


Step 9
 Add a hidden button control to activate modal PopUp,it is look like this
<asp:Button ID="btnControl" runat="server" style="display:none" />


Step 10
Add a Extender to Panel Control,it is look like this


Click on Image for better view


Click on Add Extender link and Extender Wizard dialog box will be open and select ModalPopUpExtender and click on OK button.




Click on Image for better view

<asp:ModalPopupExtender ID="PnlEmployee_ModalPopupExtender" runat="server" 
                                DynamicServicePath="" Enabled="True" TargetControlID="btnControl" 
                                PopupControlID="PnlEmployee" BackgroundCssClass="ModalBackground" 
                                DropShadow="true" CancelControlID="btnClose">
                            </asp:ModalPopupExtender>


AJAX ModalPopUpExtender Properties



  1. TargetControlID
    • The ID of the element that activates the modal popup
  2. PopupControlID
    • The ID of the element to display as a modal popup
  3. BackgroundCssClass
    • The CSS class to apply to the background when the modal popup is displayed
  4. DropShadow
    • True to automatically add a drop-shadow to the modal popup
  5. CancelControlID
    • The ID of the element that cancels the modal popup


Finally Design part done now we switch into Code behind Part.


Step 10
Create a Employee static class in app_code folder for retriving an employee data from database,it is look like this

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.SqlClient;  

public static class Employee
{
    /// 
    ///  Get Employee Data from Northwind Database
    /// 
    /// DataTable
    public static  DataTable GetEmployeeData()
    {
        try
        {
            SqlConnection SqlCon = new SqlConnection(@"Data Source=SHREE\SHREE;Initial Catalog=Northwind;Integrated Security=True");
            SqlCon.Open();

            SqlCommand SqlComm = new SqlCommand("SELECT * FROM Employees", SqlCon);
            DataTable Table = new DataTable();

            SqlDataAdapter SqlDa = new SqlDataAdapter(SqlComm);
            SqlDa.Fill(Table);

            return Table;
        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message); 
        }
    }
}


Step 11
Bind Employee data to GridView,it is look like this

protected void Page_Load(object sender, EventArgs e)
    {

        if (IsPostBack == false)
        {
            BindEmployeeData();
        }
    }

    #region Method

    /// 
    ///  Bind Employee Data to GridView
    /// 
    private void BindEmployeeData()
    {
        try
        {

            DataTable Table = Employee.GetEmployeeData();

            if (Table != null)
            {
                if (Table.Rows.Count > 0)
                {
                    GvEmployee.DataSource = Table;
                    GvEmployee.DataBind();
                }
            }

            
        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message); 
        }
    }

    #endregion


Step 12
Write a below code in click event of LinkButton in GridView to populate details,it is look like this

protected void btnLinkView_Click(object sender, EventArgs e)
    {
        try
        {

            LinkButton btnLinkView = sender as LinkButton;

            GridViewRow GVEmployeeRow =(GridViewRow) btnLinkView.NamingContainer;

            lblFirstName.Text = GVEmployeeRow.Cells[1].Text.Trim();
            lblLastName.Text = GVEmployeeRow.Cells[2].Text.Trim();
            lblBirthDate.Text = GVEmployeeRow.Cells[3].Text.Trim();
            lblCity.Text = GVEmployeeRow.Cells[4].Text.Trim();

            PnlEmployee_ModalPopupExtender.Show();

        }
        catch (Exception)
        { }
    }


Run the Project.


Output


Click on Image for better view


Full Source Code


1. .Aspx Code
<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>

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

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

    <style type="text/css">
    
             .ModalBackground
            {
                  background-color: Gray;
                  filter: alpha(opacity=60);
                  opacity: 0.6;
                  z-index: 10000;
            }
 
            .ModalPopup
            {
                  background-color:White;
                  border-width:3px;
                  border-style:solid;
                  border-color:Gray;
                  padding:5px;
                  width: 350px; <%--Change width of the panel--%>
                  height:210px;<%-- Change height of the Panel--%>
            }
       
    </style>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server">
        </asp:ToolkitScriptManager>
        
        <asp:UpdatePanel ID="UpdatePanel1" runat="server">
            
            <ContentTemplate>
                
                            
                            <asp:GridView ID="GvEmployee" runat="server" AutoGenerateColumns="False" 
                                BackColor="White" BorderColor="#999999" BorderStyle="Solid" BorderWidth="1px" 
                                CellPadding="3" EnableModelValidation="True" ForeColor="Black" 
                                GridLines="Vertical">
                                <AlternatingRowStyle BackColor="#CCCCCC" />
                                <Columns>
                                    <asp:TemplateField>
                                        <ItemTemplate>
                                            <asp:LinkButton ID="btnLinkView" runat="server" onclick="btnLinkView_Click">View</asp:LinkButton>
                                        </ItemTemplate>
                                    </asp:TemplateField>
                                    <asp:BoundField DataField="FirstName" HeaderText="FirstName" />
                                    <asp:BoundField DataField="LastName" HeaderText="LastName" />
                                    <asp:BoundField DataField="BirthDate" HeaderText="BirthDate" />
                                    <asp:BoundField DataField="City" HeaderText="City" />
                                </Columns>
                                <FooterStyle BackColor="#CCCCCC" />
                                <HeaderStyle BackColor="Black" Font-Bold="True" ForeColor="White" />
                                <PagerStyle BackColor="#999999" ForeColor="Black" HorizontalAlign="Center" />
                                <SelectedRowStyle BackColor="#000099" Font-Bold="True" ForeColor="White" />
                            </asp:GridView>
                          
                  
                            
                            <asp:Panel ID="PnlEmployee" runat="server" CssClass="ModalPopup" style="display:none">
                                    
                                    <table border="1" cellpadding="5" cellspacing="5" width="100%" align="center" style="border-color: #FF6600">
                                            <tr>
                                                <td>First Name</td>
                                                <td><asp:Label ID="lblFirstName" runat="server"></asp:Label></td>
                                            </tr>
                                             <tr>
                                                <td>Last Name</td>
                                                <td><asp:Label ID="lblLastName" runat="server"></asp:Label></td>
                                            </tr>
                                            <tr>
                                                <td>BirthDate</td>
                                                <td><asp:Label ID="lblBirthDate" runat="server"></asp:Label></td>
                                            </tr>
                                            <tr>
                                                <td>City</td>
                                                <td><asp:Label ID="lblCity" runat="server"></asp:Label></td>
                                            </tr>
                                            <tr align="center" valign="middle">
                                                <td colspan="2">
                                                    <asp:Button ID="btnClose" runat="server" Text="Close" />
                                                </td>
                                            </tr>

                                    </table>
                                                                    
                            </asp:Panel>

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

                            <asp:ModalPopupExtender ID="PnlEmployee_ModalPopupExtender" runat="server" 
                                DynamicServicePath="" Enabled="True" TargetControlID="btnControl" 
                                PopupControlID="PnlEmployee" BackgroundCssClass="ModalBackground" 
                                DropShadow="true" CancelControlID="btnClose">
                            </asp:ModalPopupExtender>

                      

            </ContentTemplate>

        </asp:UpdatePanel>

    </div>
    </form>
</body>
</html>

2.Code Behind
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;

public partial class _Default : System.Web.UI.Page 
{
    protected void Page_Load(object sender, EventArgs e)
    {

        if (IsPostBack == false)
        {
            BindEmployeeData();
        }
    }

    #region Method

    /// 
    ///  Bind Employee Data to GridView
    /// 
    private void BindEmployeeData()
    {
        try
        {

            DataTable Table = Employee.GetEmployeeData();

            if (Table != null)
            {
                if (Table.Rows.Count > 0)
                {
                    GvEmployee.DataSource = Table;
                    GvEmployee.DataBind();
                }
            }

            
        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message); 
        }
    }

    #endregion

    protected void btnLinkView_Click(object sender, EventArgs e)
    {
        try
        {

            LinkButton btnLinkView = sender as LinkButton;

            GridViewRow GVEmployeeRow =(GridViewRow) btnLinkView.NamingContainer;

            lblFirstName.Text = GVEmployeeRow.Cells[1].Text.Trim();
            lblLastName.Text = GVEmployeeRow.Cells[2].Text.Trim();
            lblBirthDate.Text = GVEmployeeRow.Cells[3].Text.Trim();
            lblCity.Text = GVEmployeeRow.Cells[4].Text.Trim();

            PnlEmployee_ModalPopupExtender.Show();

        }
        catch (Exception)
        { }
    }


}


Download
Download Source Code

6 comments:

  1. Hi Kishore, how to avoid page reload while clicking view button... the popup window is displaying by reloading the whole page, I don't want to refresh the page I tried by keeping its not working.. plz help me......

    ReplyDelete
    Replies
    1. Hi Kishore, how to avoid page reload while clicking view button... the popup window is displaying by reloading the whole page, I don't want to refresh the page I tried by keeping updatepanel and contenttemplete tags its not working.. plz help me......

      Delete
  2. Very Good Coding and Explanation.........

    ReplyDelete