ModalPopupExtender Example for Editing Rows in a GridView (Master/Detail Scenario)

The web application I am currently working on is a data-centric, internal facing application targeted at the knowledge workers within our enterprise.  A majority of the pages are our core 'search' pages that contain a GridView and a number of input elements for entering search criteria.  Each row in our GridViews contain a hyperlink to a supporting 'details' page that has additional information for the selected row - usually contained in a DetailsView.  Our standard for implementing this has been to render the values for the GridViews primary key column as a hyperlink that takes the user to the details page passing the PK through the query string.  This all works fine and our users seem to be OK with this type of naviagation.  But when I was recently doing some work with the ModalPopupExtender, I was curious if we could improve this flow by keeping the user on the main search page by moving the DetailsView to the ModalPopupExtender.  See the screen shot below or the live demo for an example.

Live Demo | Download Code

I did a few google searches, and sure enough there were some people doing this (here and here).  I took a similiar approach to the second article, but with a few minor tweaks.  I uploaded a live demo of these pages so you can check out the behavior (I kept the styling to a minimum as usual).  The code for this example is straight-forward except for the following 3 items:

1.  The ModalPopupExtender requires the TargetControlID property to be set.  Because of this I created a hidden button so this error doesn't occur.  For this example, we don't need to set a control to trigger the popup because we are always explicitly calling Show() on the popup when the Details button is clicked).

2.  The DetailsView for the selected row is contained in an updatepanel with the UpdateMode set to Conditional.  This is done because we want to make sure that the control is only updated from the Details button click handler and not when the Customers GridView is sorted or paged through

3.  We are explicitly calling Show on the ModalPopup to display the DetailsView from the 'Details' button click event.  This is the only action that triggers the ModalPopup from being made visible

 

Also, I didn't actually implement an update because I don'y want my northwind database getting messed up.  Hopefully this will get you enough of a start that implementing the update will not be a huge problem.

Here is the markup for the page, Enjoy!

<%@ Page Language="C#" %>
<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="ajaxToolkit" %>

<!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="head" runat="server">
    <title>Master Details Example</title>
    <script runat="server">
  
    
    /// <summary>
    /// 
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void BtnViewDetails_Click(object sender, EventArgs e)
    {
        //  get the gridviewrow from the sender so we can get the datakey we need
        Button btnDetails = sender as Button;
        GridViewRow row = (GridViewRow)btnDetails.NamingContainer;
        
        //  extract the customerid from the row whose details button originated the postback.
        //  grab the customerid and feed it to the customer details datasource
        //  finally, rebind the detailview
        this.sqldsCustomerDetails.SelectParameters.Clear();
        this.sqldsCustomerDetails.SelectParameters.Add("customerid", Convert.ToString(this.gvCustomers.DataKeys[row.RowIndex].Value));
        this.dvCustomerDetail.DataSource = this.sqldsCustomerDetails;
        this.dvCustomerDetail.DataBind();

        //  update the contents in the detail panel
        this.updPnlCustomerDetail.Update();
        //  show the modal popup
        this.mdlPopup.Show();
    }   
    
    </script>
    <style>
        .modalBackground {
            background-color:Gray;
            filter:alpha(opacity=70);
            opacity:0.7;
        }
    </style>
</head>
<body>
    <form id="form" runat="server">
        <asp:ScriptManager ID="scriptManager" runat="server" />
        <div>
            <asp:SqlDataSource ID="sqldsCustomers" runat="server" 
                SelectCommand="select customerid, companyname, contactname, contacttitle from dbo.customers"
                SelectCommandType="Text" ConnectionString="todo" />
            <asp:SqlDataSource ID="sqldsCustomerDetails" runat="server" 
                SelectCommand="select * from dbo.customers where customerid=@customerid"
                SelectCommandType="Text" CancelSelectOnNullParameter="true" ConnectionString="todo"/>
            
            <p style="background-color:AliceBlue; width:95%">
                Example of using a ModalPopupExtender to edit the indivdual rows of a GridView.<br />
                To test out the functionality, click the Details button of any of the rows and watch what happens.<br />
            </p>
            
            <br />
            <asp:UpdatePanel ID="updatePanel" runat="server" UpdateMode="Conditional">
                <ContentTemplate>            
                    <asp:Label ID="lblTitle" runat="server" Text="Customers" BackColor="lightblue" Width="95%" />
                    <asp:GridView 
                        ID="gvCustomers" runat="server" DataKeyNames="customerid" AutoGenerateColumns="false" 
                        AllowPaging="true" AllowSorting="true" PageSize="10" DataSourceID="sqldsCustomers" Width="95%">
                        <AlternatingRowStyle BackColor="aliceBlue" />
                        <HeaderStyle HorizontalAlign="Left" />
                        <Columns>
                            <asp:TemplateField ControlStyle-Width="50px" HeaderStyle-Width="60px">
                                <ItemTemplate>
                                    <asp:Button ID="btnViewDetails" runat="server" Text="Details" OnClick="BtnViewDetails_Click" />
                                </ItemTemplate>
                            </asp:TemplateField>
                            <asp:BoundField DataField="customerid" HeaderText="ID" SortExpression="customerid" ReadOnly="true" />
                            <asp:BoundField DataField="companyname" HeaderText="Company" SortExpression="companyname" ReadOnly="true" />
                            <asp:BoundField DataField="contactname" HeaderText="Name" SortExpression="contactname" ReadOnly="true" />
                            <asp:BoundField DataField="contacttitle" HeaderText="Title" SortExpression="contacttitle" ReadOnly="true" />                
                        </Columns>                    
                    </asp:GridView>
                </ContentTemplate>
            </asp:UpdatePanel>                    
            
            <asp:Button id="btnShowPopup" runat="server" style="display:none" />
            <ajaxToolKit:ModalPopupExtender 
                ID="mdlPopup" runat="server" TargetControlID="btnShowPopup" PopupControlID="pnlPopup" 
                CancelControlID="btnClose" BackgroundCssClass="modalBackground" />
            <asp:Panel ID="pnlPopup" runat="server" Width="500px" style="display:none">
                <asp:UpdatePanel ID="updPnlCustomerDetail" runat="server" UpdateMode="Conditional">
                    <ContentTemplate>
                        <asp:Label ID="lblCustomerDetail" runat="server" Text="Customer Detail" BackColor="lightblue" Width="95%" />
                        <asp:DetailsView ID="dvCustomerDetail" runat="server" DefaultMode="Edit" Width="95%" BackColor="white" />
                    </ContentTemplate>                
                </asp:UpdatePanel>
                <div align="right" style="width:95%">
                    <asp:Button 
                        ID="btnSave" runat="server" Text="Save" 
                        OnClientClick="alert('Sorry, but I didnt implement save because I dont want my northwind database getting messed up.'); return false;" 
                        Width="50px" />
                    <asp:Button ID="btnClose" runat="server" Text="Close" Width="50px" />
                </div>             
            </asp:Panel>
        </div>
    </form>
</body>
</html>

TrackBack

TrackBack URL for this entry:
http://mattberseth.com/blog-mt/mt-tb.fcgi/42

Listed below are links to weblogs that reference ModalPopupExtender Example for Editing Rows in a GridView (Master/Detail Scenario):

» August 2nd Links: ASP.NET AJAX and the ASP.NET AJAX Control Toolkit from ScottGu's Blog
Here is the latest in my semi-regular link-listing series . Today's links are all about ASP.NET AJAX [Read More]

» ModalPopupExtender for Editing Rows in a GridView (Master/Deta from DotNetKicks.com
You've been kicked (a good thing) - Trackback from DotNetKicks.com [Read More]

» ModalPopupExtender Example for Editing Rows in a GridView from ASP.NET AJAX Toolkit Forum Posts
I downloaded this code http://mattberseth.com/blog/2007/07/modalpopupextender_example_for.html I am getting [Read More]

Comments


Posted by: Stevishere on July 24, 2007 12:00 AM

It seems some of the text was cut off by the page width in your code above.

Could you kindly repost or let us donload the code? (VB and C#?)

Posted by: Prashant C on August 9, 2007 12:00 AM

Could you expain or provide code to show model pop up on page load insted invoking by Button Click events

Posted by: Srinivas Reddy K on September 17, 2007 12:00 AM


hi sir,

I am student, learning asp.net,

i have a problem in updting details view.

pls, can u provide me the update part of your program sir

Posted by: Timo on September 25, 2007 12:00 AM

Matt,

Did you ever experience any issues with validators inside ModalPopup ? I have been trying to figure out why client side validation fails when using RequiredFieldValidator inside ModalPopupControl (which is displayed when editing GridView row). After clearing a field and pressing tab to proceed to next field, validator is activated. But when pressing Update-button, I can see that validator gives an error message, but at the same time ModalPopup disappears and data is processed (so that I can update an empty value to DB which is something that I dont want)

Posted by: Pete D on October 1, 2007 12:00 AM

This article would have been brilliant if it had shown how to save. I can understand why there is no save in the demo, but why not in the code shown above, or the download. I have tried hard to work it out, but failed. Is there anyone who can help please. I am sure an answer would be greatly appreciated by many people.
Thanks.

Posted by: Donald Shaw on October 22, 2007 12:00 AM

Sorry Mat, but the save data portion of the demo is, like, totally not obvious.
How about an update to the download so that we are both happy. You still save your database, and your readers will be enlightened!

Thanks.

Posted by: PtitZef on November 1, 2007 12:00 AM

About the update, i realized the following function... please, tell me what you think about this option :

protected void SaveDetails(object sender, EventArgs e)
{
IOrderedDictionary keyList = dvCustomerDetail.DataKey.Values;

// Get the ArrayList objects that represent the key values.
ArrayList values = new ArrayList(keyList.Values);

// Get the key field and value for the current record.
String customerKey = values[0].ToString();

this.sqldsCustomerDetails.UpdateParameters.Add("customerid", customerKey );
this.sqldsCustomerDetails.UpdateParameters.Add("companyname", ((TextBox)dvCustomerDetail.Rows[0].Cells[1].Controls[0]).Text);
...
this.sqldsCustomerDetails.Update();

this.gvCustomers.DataBind();
}

Posted by: Paul on November 6, 2007 12:00 AM

Hi Sir,

I am using "Ajax Extentions" that meet some issues such as Im using master pages with my tab control on a content page.
how to click "BtnViewDetails_Click" on first tab to display all data have customerid=@customerid on second tab!
pls, can u provide me the sample program sir!
Paul

Posted by: Carl Edwards on November 19, 2007 12:00 AM

Very nice Matt, works a charm... but... please tell me the secret... how do I stop the pop up panel "remembering" the scroll postion! I have a pop up where the content exceeds the depth sometimes. This means I scroll down to click the close button and the next time the window pops up, it scrolls to wherever I was last time!

Its driving me mad! Can anyone help put me out of my misery please? I just want it to always scroll back to the top when I open the popup!

Posted by: Ryan_ on November 20, 2007 12:00 AM

Hi Matt,

One question, As I keep on ModalPopupExtender to make PostBack?

Thanks.

thanks for the GREAT post! Very useful...

Posted by: zhouxing on November 26, 2007 12:00 AM

i am chinese ,i have a problem,where are your connectionString?

Posted by: PtitZef on November 26, 2007 12:00 AM

Your ConnectionString is in your web.config (in the section) . Then, you select your ConnectionString in the DataSource.

Posted by: Mad on December 17, 2007 12:00 AM

Hi Matt,

With asp.net, I have yet to figure out how to best implement a really neat feature and that is the COPY option on each row on the GridView.

When the Copy is clicked on a row, it goes to the Detail View with all the fields prefilled from the row that was clicked and allow user to make any changes and INSERT a new record - the detail view being shown in INSERT Mode.

Ideally - I would like to reuse the Detail View for both UPDATE and INSERT mode where UPDATE (makes the key field readonly) while INSERT allows you to set the key or hide the key if it is a autonumber/integer assigned by database using the IDENTITY column.

Thanks
Mad

Posted by: hans on December 29, 2007 12:00 AM

I agree with tim...The most difficult part is how to update when ok button is clicked?

Posted by: Eugen on January 3, 2008 12:00 AM

Can anyone tell me how can I use update command...?
Thanks!!

Posted by: VonBondies on January 3, 2008 12:00 AM

I want my database get messed up!!

Posted by: Anonymous on January 8, 2008 12:00 AM

hi how u show the loading gif file whe i click the view details button inside the grid........

Posted by: MUNISH on January 10, 2008 12:00 AM

How can I add the value in a gridview column directly from the modal popup extender. I dont want to update the datasource, but want to directly show the value from modalpopup textbox to a gridview column.

Thanks.

Posted by: CynicalVanth on January 17, 2008 12:00 AM

works like a charm!

however... cant figure out what the save portion is supposed to be like. is there still no update on this?

appreciate it much! thanks!

great work, by the way.

Posted by: Greg B on January 25, 2008 12:00 AM

Here is what I did for the save, although its probably not the most elegant solution...
Note: The controls below are not in the tutorial. It has been adapted to suit my needs. This goes in the click event of your save button.

Dim alertid As String = dvConfiguration.DataKey.Value.ToString
Dim description As TextBox = CType(dvConfiguration.FindControl("txtdescription"), TextBox)


Dim strSQL As String = "mm_UpdateAlert"
Dim con As New SqlConnection(AuditConnectionString)
Dim cmd As New SqlCommand(strSQL, con)
cmd.CommandType = CommandType.StoredProcedure

Dim pDescription As SqlParameter = cmd.Parameters.Add("@description", SqlDbType.VarChar)
pDescription.Value = description.Text

Dim pAlertId As SqlParameter = cmd.Parameters.Add("@alertid", SqlDbType.VarChar)
pAlertId.Value = alertid

Try
con.Open()
cmd.ExecuteNonQuery()
con.Close()
The idea is to pull the datakey of the details view for the "where" portion of the SQL clause. Then declare all the controls in your details view so you can grab their text values. From there its just a matter of inputting them into your SQL command string for the update.

Thanks Matt for writing such a great tutorial!

Posted by: avinash on January 29, 2008 12:00 AM

solved my problem.
really good article.
thank u very much.

Posted by: iceBreaker on March 1, 2008 12:00 AM

Hello Sir,

I would like to do the same thing but with a listview instead of a gridview. Is it possible?
Also, I would like to insert data to the listview using the popout method...
Thanks,

Posted by: nelson on March 7, 2008 12:00 AM

Hi Matt,
I noticed in your live demo that theres an animation playing before the modal popup display, but I cant find any reference to that in the sample code. Can you kindly please share how you achieve that? Sorry but Im a beginner to ajax.net. Thank you very much

Paul Im having the same problem...

"how do I stop the pop up panel "remembering" the scroll postion!"

Matt?

Posted by: Asif on March 19, 2008 12:00 AM

Cool Article. Thanks For Excellent Tip.

Posted by: Jiminey on March 28, 2008 12:00 AM

Hi,

I am new with ajaxtoolkit. we are using modalpopup for project at work. Now I have to include a TabContainer within the modalpopup. When I add a textbox within the TabContainer/TabPanel, the textboxes are null. I have tried the textboxes outside the TabContainer and they are fine. I am able to render the textboxes but once I try to save and get the values from the textboxes, I received errors saying they are null.

Could anyone help please? Thanks so much!

Posted by: Neetu on April 1, 2008 12:00 AM

requirePermission attribute is not declared...this type of lot of problems i m facing while run ur downloaded program

Posted by: Neetu on April 1, 2008 12:00 AM

Could not load file or assembly System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35 or one of its dependencies. The system cannot find the file specified. (D:NeetuProjets Backupwebrootweb.config line 40)
this is another error...and a lot of errors....please help me

Posted by: Neetu on April 2, 2008 12:00 AM

Please tell us how to update/save the record from here

Posted by: Dan on April 8, 2008 12:00 AM

I have converted the code to VB but im getting the following error on this line: Me.mdlPopup.Show() Error = "mdlPopup is not a member of Page_Name". Any ideas?

Posted by: sunrfun on April 19, 2008 12:00 AM

How to Check there TextBoxs date is validate when USE ModelPopulExtender

For all that wanted to know how to get it to scroll back to the top. You can do this with som script code:
// scroll back to the top of the list
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_endRequest(
function(){
window.scrollTo(0,580);
}
);
Take note of the scrollTo(x,y) function. You will have to modify those arguments to scroll to a position relative to your webpage. Hope this helps.

Posted by: mick on April 26, 2008 12:00 AM

Folks,
Has anyone tried including the cascadingdropdown control in the modalpopup panel.

I have attempted this several times but no joy. All sorts of problems on postback

Posted by: kevin on April 30, 2008 12:00 AM

In your live demo, when you enter any html code(or just even a "

eg. when you first time click "details" button, in any textbox(eg. in City texbox, enter ) and click no matter "Save" or "Close". And then click on any "details" button again, then, you will see the error.Do you know how/why this happens?

Posted by: kevin on May 1, 2008 12:00 AM

oh. it seems I cannot enter a > in the comment too.

In your live demo, when you enter any html code(or just even a "

eg. when you first time click "details" button, in any textbox(eg. in City texbox, enter "") and click no matter "Save" or "Close". And then click on any "details" button again, then, you will see the error.

Do you know how/why this happens?

Posted by: Shailendra on May 2, 2008 12:00 AM

Pls show update/save code here..

Thanks in anvance

I have created an example that includes updating/saving the data. You can check it out here

Posted by: Arnab das on May 5, 2008 12:00 AM

I want to have the id of the textbox inside the DetailsView.How it can be achieved?

Posted by: Rakesh on May 8, 2008 12:00 AM

Validators will not work on modal popup and you will require to create item templates for it and bind them individually

Posted by: Chau on May 30, 2008 12:00 AM

Just out curiousity. I have a mainpage that calls a usercontrol that is in a modal popup. The usercontrol has a gridview and I want to implement your modal popup detail example. Is it possible to nest modal popup within another one? Is that bad design?

Saved my day! Was digging asp.net forum and found this link. Very valuable. Code is easy to understand.

Keep adding more, Matt.

Best wishes
Tom

Posted by: Neetu on July 4, 2008 12:00 AM

my page is posting back while modalpopupextender is displaying...please help me

Posted by: bons on July 15, 2008 12:00 AM

hi anybody help me out how I can do with postgressql its urgent and just tell me where should I change code or just give me code if it is possible

( I want to transfer data from parent widnow to modalpopup and then after updating in modalpopup go back to parent window with new value.

Please help me out its really very urgent

Thanks a lot in advance

Bons

Posted by: sumalatha on July 17, 2008 12:00 AM

hiiiiiiiii
plese provide me the save button code to update the values of details view

Posted by: Wilson/TI on August 5, 2008 12:53 PM

Thank your good example, it has been reviewed here in Brazil

I am getting this error. Compiler Error Message: CS1061: 'ASP.webroot_default_aspx' does not contain a definition for 'mdlPopup' and no extension method 'mdlPopup' accepting a first argument of type 'ASP.webroot_default_aspx' could be found (are you missing a using directive or an assembly reference?)

Line 32 this.mdlPopup.Show();
Any help please.

I am new to asp. I downloaded your code. I like it a lot.

Please I need help with only one thing that is; how to
implement an update. What should be OnClientClick= ?

Thanks again.

Juvan

Posted by: Von on October 16, 2008 03:24 AM

please show us how to update the database..
thanks!

Posted by: Phill Beeke on October 25, 2008 02:39 AM

Please couls you show the location where the update part for this sollution is. Thanks in advance

Phill

Posted by: Joshua Neal on October 29, 2008 10:29 AM

Great post .... by using your example below. I was able to get around the issues that were occuring with the PopUpExtender. I would suggest using this solution for the ModalPopUpExtender rather than using the regular PopUpExtender.


Once again ... great post.

Post a comment

(If you haven't left a comment here before, you may need to be approved by the site owner before your comment will appear. Until then, it won't appear on the entry. Thanks for waiting.)

Consulting Services

Yep - I also offer consulting services. And heck, I'll do just about anything. If you enjoy my blog just drop me an email describing the work you need done.

Recent Comments

  • Joshua Neal wrote: Great post .... by using your example below. I was able to get around the issues that were occuring ...
  • Phill Beeke wrote: Please couls you show the location where the update part for this sollution is. Thanks in advance ...
  • Von wrote: please show us how to update the database.. thanks!...
  • Juvan wrote: I am new to asp. I downloaded your code. I like it a lot. Please I need help with only one thing th...
  • Heval wrote: I am getting this error. Compiler Error Message: CS1061: 'ASP.webroot_default_aspx' does not contain...
  • Wilson/TI wrote: Thank your good example, it has been reviewed here in Brazil...
  • sumalatha wrote: hiiiiiiiii plese provide me the save button code to update the values of details view ...
  • bons wrote: hi anybody help me out how I can do with postgressql its urgent and just tell me where should I chan...