Display Master-Detail Data with the ModalPopup Extender and GridView
In the past we have often used the combination of the GridView and DetailsView to display Master-Detail data. Similarly, developers have used pop-ups to depict similar scenarios where a user clicks on a ‘master’ row and the details are displayed in a pop-up window. I was recently exploring the ModalPopup extender control which allows a page to display content to the user in a "modal" manner. To explore the control, I thought of trying out the Master-Details scenario using the ModalPopup Extender. Here’s what we will do.
We will display an Order-Customer scenario using the ModalPopup extender. For demonstration purposes, we will be using the ‘Orders’ and ‘Customers’ table from the Northwind database. We will initially fetch and display data from the ‘Orders’ table in a GridView. The CustomerID will be a link which will enable the user to view details of the Customer using a ModalPopup Extender. The example focuses on exploring the capabilities of the ModalPopup Extender and hence less weightage has been given to ‘best practices of fetching data’ or realisitic usage of this control.
Note: I am using Visual Studio 2008 and thereby utilizing the ASP.NET AJAX plumbing that comes along with it.
Let us get started with a Step-by-Step approach to do so. Viewers who have prior experience in configuring the SqlDataSource, can jump directly to Step 5:
Step 1: Open VS 2008. Click File > New > Website. Choose ASP.NET Website from the list of installed template, choose target platform as .NET Framework 3.5, choose the desired language and enter the location where you would like to store the website on your FileSystem. I have created a folder called VS2008 Projects, so the location over here is C:\VS2008 Projects\ GridViewModalPopupExtender. After typing the location, click OK.
Step 2: Open Default.aspx. Switch to the Design mode of Default.aspx. Open the toolbox (Ctrl+Alt+X) > Data Tab > Drag and drop a SqlDataSource control on to the form. Click on the smart tag or right click SqlDataSource > Show Smart Tag > ‘Configure Data Source’ wizard. Click on ‘New Connection’ to open the ‘Add Connection’. Type your ‘Server Name’ and ‘Select a database Name’ to connect to. Over here, I have used (local) as the ‘ServerName’ and the database I am connecting to, is Northwind. Click on ‘Test Connection’ to make sure that there are no errors while connecting to the server. Click Ok.
Step 3: In your ‘Configure Data Source’, click ‘Next’. An option will be displayed to save the connection string to the configuration file. Select the checkbox ‘Yes, save this connection as:’, type a name for the connectionstring ‘NorthwindConnectionString’ and click Next.
Step 4: In the ‘Configure Select Statement’ > select ‘Specify Columns from Tables or Views’ radiobutton > Select ‘Orders’ table in the Name and choose OrderID, CustomerID, OrderDate and ShippedDate. Click Next > ‘Test Query’ to preview data > click Finish. The wizard adds a SqlDataSource control to the page as shown below.
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString %>"
SelectCommand="SELECT [OrderID],[CustomerID],[OrderDate],[ShippedDate] FROM [Orders]"></asp:SqlDataSource>
If you check your web.config, the connection string is added as shown below:
<connectionStrings>
<add name="NorthwindConnectionString" connectionString="Data Source=(local);Initial Catalog=Northwind;Integrated Security=True" providerName="System.Data.SqlClient"/>
</connectionStrings>
Step 5: Add a <ScriptManager> control to the page and then an <UpdatePanel> from the toolbox. Drag and drop a GridView from the toolbox and place it inside the <UpdatePanel> and set its data source property to the 'SqlDataSource1' as shown below:
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:GridView ID="GridView1" runat="server" DataSourceID="SqlDataSource1"
AutoGenerateColumns="false" AllowPaging="true" >
</asp:GridView>
</ContentTemplate>
</asp:UpdatePanel>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString %>"
SelectCommand="SELECT [OrderID],[CustomerID],[OrderDate],[ShippedDate] FROM [Orders]"></asp:SqlDataSource>
</form>
</body>
Step 6: We will now add columns to the GridView as shown below. Observe that the CustomerID is displayed as a link. We will display the CustomerDetails when the user clicks on the link.
<asp:GridView ID="GridView1" runat="server" DataSourceID="SqlDataSource1"
AutoGenerateColumns="false" AllowPaging="true" >
<Columns>
<asp:BoundField HeaderText="OrderID" DataField="OrderID" />
<asp:TemplateField HeaderText="CustomerID">
<ItemTemplate>
<asp:LinkButton runat="server" ID="lnkCustDetails" Text='<%# Eval("CustomerID") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField HeaderText="OrderDate" DataField="OrderDate" />
<asp:BoundField HeaderText="ShippedDate" DataField="ShippedDate" />
</Columns>
</asp:GridView>
Step 7: We will now add a ModalPopup Extender below the GridView:
<asp:Button runat="server" ID="btnShowModalPopup" style="display:none"/>
<cc1:ModalPopupExtender ID="ModalPopupExtender1" runat="server"
TargetControlID="btnShowModalPopup"
PopupControlID="divPopUp"
BackgroundCssClass="popUpStyle"
PopupDragHandleControlID="panelDragHandle"
DropShadow="true"
/>
<br />
<div class="popUpStyle" id="divPopUp" style="display:none;">
<asp:Panel runat="Server" ID="panelDragHandle" CssClass="drag">
Hold here to Drag this Box
</asp:Panel>
<asp:Label runat="server" ID="lblText" Text="CustomerID: "></asp:Label>
<asp:Label ID="lblCustValue" runat="server"></asp:Label>
<asp:GridView ID="GridView2" runat="server">
</asp:GridView>
<asp:Button ID="btnClose" runat="server" Text="Close" />
<br />
</div>
The ModalPopup Extender has a number of properties that are as follows:
· TargetControlID – The ID of the element that activates the modal popup; in our case it is the ‘btnShowModalPopup’
· PopupControlID - The control that will be displayed as the modal popup; in our case it is the <div> called ‘divPopUp’
· PopupDragHandleControlID - The ID of the popup header which will be used to drag the modal popup on the page; in our case it is the panel ‘panelDragHandle’.
There are some other properties like the BackgroundCssClass, DropShadow etc. which modify the appearance of the popup. To know more about the other properties of the ModalPopup Extender, check this link.
The divPopUp and panelDragHandle make use of css which is declared as shown below:
<head id="Head1" runat="server">
<title>GridView With ModalPopUpExtender</title>
<style type="text/css">
body
{
font: normal 12px auto "Trebuchet MS", Verdana;
background-color: #ffffff;
color: #4f6b72;
}
.popUpStyle
{
font: normal 11px auto "Trebuchet MS", Verdana;
background-color: #ffffff;
color: #4f6b72;
padding:6px;
filter: alpha(opacity=80);
opacity: 0.8;
}
.drag
{
background-color: #dddddd;
cursor: move;
border:solid 1px gray ;
}
</style>
</head>
The divPopUp also contains the GridView control to display the CustomerDetails. If you have to display only read-only data, you can use a lighter control like the Repeater instead of the GridView.
Step 8: The last step is to invoke the ModalPopup and populate the GridView2 with the CustomerDetails; the user has requested for. Add a click event to the LinkButton and add the following code in the event handler
<asp:LinkButton runat="server" ID="lnkCustDetails" Text='<%# Eval("CustomerID") %>' OnClick="lnkCustDetails_Click" />
C#
protected void lnkCustDetails_Click(object sender, EventArgs e)
{
// Fetch the customer id
LinkButton lb = sender as LinkButton;
string custID = lb.Text;
lblCustValue.Text = custID;
// Connection
string constr = System.Web.Configuration.WebConfigurationManager.
ConnectionStrings["NorthwindConnectionString"].ConnectionString;
string sql = "SELECT CompanyName, ContactName, Address FROM Customers WHERE CustomerID = @CustID";
SqlConnection connection = new SqlConnection(constr);
SqlCommand cmd = new SqlCommand(sql, connection);
cmd.Parameters.AddWithValue("@CustID", custID);
cmd.CommandType = CommandType.Text;
connection.Open();
SqlDataReader dr = cmd.ExecuteReader();
// Bind the reader to the GridView
// You can also use a lighter control
// like the Repeater to display data
GridView2.DataSource = dr;
GridView2.DataBind();
connection.Close();
// Show the modalpopupextender
ModalPopupExtender1.Show();
}
VB.NET
Protected Sub lnkCustDetails_Click(ByVal sender As Object, ByVal e As EventArgs)
' Fetch the customer id
Dim lb As LinkButton = TryCast(sender, LinkButton)
Dim custID As String = lb.Text
lblCustValue.Text = custID
' Connection
Dim constr As String = System.Web.Configuration.WebConfigurationManager.
ConnectionStrings("NorthwindConnectionString").ConnectionString
Dim sql As String = "SELECT CompanyName, ContactName, Address FROM Customers WHERE CustomerID = @CustID"
Dim connection As New SqlConnection(constr)
Dim cmd As New SqlCommand(sql, connection)
cmd.Parameters.AddWithValue("@CustID", custID)
cmd.CommandType = CommandType.Text
connection.Open()
Dim dr As SqlDataReader = cmd.ExecuteReader()
' Bind the reader to the GridView
' You can also use a lighter control
' like the Repeater to display data
GridView2.DataSource = dr
GridView2.DataBind()
connection.Close()
' Show the modalpopupextender
ModalPopupExtender1.Show()
End Sub
Note: Remember to add the namespace System.Data.SqlClient
It’s time to run the application and test the functionality. When you run the application, a GridView with the Orders data is displayed as shown below:
On clicking on any of the CustomerID, a ModalPopup with the Customer details appears as shown below:
So that was the ModalPopup Extender for you. A lot of developers I know, have used this control to handle common scenarios like editing data or display images in pop-ups. The ModalPopup Extender is a very handy control and I hope this article has given you some insights of how to use this control. The entire source code of this article in C# and VB.NET can be downloaded from here. I hope the article was useful and I thank you for viewing it.
This article has been editorially reviewed by Suprotim Agarwal.
C# and .NET have been around for a very long time, but their constant growth means there’s always more to learn.
We at DotNetCurry are very excited to announce The Absolutely Awesome Book on C# and .NET. This is a 500 pages concise technical eBook available in PDF, ePub (iPad), and Mobi (Kindle).
Organized around concepts, this Book aims to provide a concise, yet solid foundation in C# and .NET, covering C# 6.0, C# 7.0 and .NET Core, with chapters on the latest .NET Core 3.0, .NET Standard and C# 8.0 (final release) too. Use these concepts to deepen your existing knowledge of C# and .NET, to have a solid grasp of the latest in C# and .NET OR to crack your next .NET Interview.
Click here to Explore the Table of Contents or Download Sample Chapters!
Was this article worth reading? Share it with fellow developers too. Thanks!
Suprotim Agarwal, MCSD, MCAD, MCDBA, MCSE, is the founder of
DotNetCurry,
DNC Magazine for Developers,
SQLServerCurry and
DevCurry. He has also authored a couple of books
51 Recipes using jQuery with ASP.NET Controls and
The Absolutely Awesome jQuery CookBook.
Suprotim has received the prestigious Microsoft MVP award for Sixteen consecutive years. In a professional capacity, he is the CEO of A2Z Knowledge Visuals Pvt Ltd, a digital group that offers Digital Marketing and Branding services to businesses, both in a start-up and enterprise environment.
Get in touch with him on Twitter @suprotimagarwal or at LinkedIn