Click here to Skip to main content
15,884,176 members
Articles / Web Development / ASP.NET

How to Popup a Customized Window from a GridView via OnClientClick()

Rate me:
Please Sign up or sign in to vote.
2.60/5 (3 votes)
20 Oct 2009CPOL1 min read 25K   20   3
Putting a customized popup window in a GridView in ASP.NET using C#

Introduction

I was searching for a quick way to add a customizable popup into a GridView, and after Googling for 'GridView Popup' and slowly losing patience, I realised I needed to make my own and that I needed to use JavaScript (but wanting to reuse code across a site without retyping it in each time), so I put this bit of code together.

Now that I have used it and am happy with the results, I thought I would share this with the world, just in case it could save someone else some time!

The Code

Place the code in your Helper.cs class (that's where I place it so I can reuse it over the whole site), or just put it in the background code.

C#
/// <summary>
/// Use this to Create a Popup Url in a gridview
/// For example sending CreatePopupUrl(600,450,-1,-1,false,false,false,false,
/// false,false,"http://www.google.com/{0}","video")
/// this would make a link to http://www.google.com/video
/// with a 600 pixel high, 460 pixel wide window, 
/// centred in the window, with no scrollbars, no menubar, not resizable
/// no toolbar, no nav bar, no status bar.
/// </summary>
/// <param name="windowHeight">Enter the height of the popup window  
/// (eg, 600)</param>
/// <param name="windowWidth">Enter the width of the popup window
/// (eg, 460)</param>
/// <param name="leftPosition">Enter -1 in left and top position to 
/// automatically centre the popup in the window</param>
/// <param name="topPosition">Enter -1 in left and top position to
/// automatically centre the popup in the window</param>
/// <param name="showScrollbars">If you want to show scrollbars, enter 'True'
/// <param name="showMenuBar">If you want to show the Menubar,
/// enter 'True'</param>
/// <param name="isResizable">If you want the window to be resizable,
/// enter 'True'</param>
/// <param name="showToolbar">If you want to show the toolbar, 
/// enter 'True'</param>
/// <param name="hasLocation">If you want the window to have a 
/// Navigation bar, enter 'True'</param>
/// <param name="showStatus">If you want to show status, enter 'True'</param>
/// <param name="url">Enter the string of the url
/// (eg http://www.google.com/{x}) (this will replace the {x} 
/// with what index your args are in) </param>
/// <param name="args">Enter the parameters you want to add to the url. </param>
/// <returns></returns>
public static string CreatePopupUrl(double windowHeight,
                                    double windowWidth,
                                    double leftPosition,
                                    double topPosition, 
                                    bool showScrollbars, 
                                    bool showMenuBar, 
                                    bool isResizable, 
                                    bool showToolbar, 
                                    bool hasLocation, 
                                    bool showStatus, 
                                    string url, 
                                    params object[] args)
{
    string strShowScrollbars = showScrollbars ? "yes" : "no";
    string strShowMenuBar = showMenuBar ? "yes" : "no";
    string strIsResizable = isResizable ? "yes" : "no";
    string strShowToolbar = showToolbar ? "yes" : "no";
    string strHasLocation = hasLocation ? "yes" : "no";
    string strShowStatus = showStatus ? "yes" : "no";
    url = string.Format(url, args);
    double finalLeftPosition = leftPosition;
    double finalTopPosition = topPosition;
    if (leftPosition == -1)
    { 
        //Automatically Horizontally centre the window
        //If the Screen not null
        try
        {
            if (Screen.PrimaryScreen != null)
            {
                finalLeftPosition = 
                  (((double)Screen.PrimaryScreen.Bounds.Width / 2) - 
                   (windowWidth / 2));
               
            }
        }
        catch (Exception)
        {
            //If there was an error, just set the Final Positions to 0
            finalLeftPosition = 0;
        }
    }

    if (topPosition == -1)
    {
        //Automatically Vertically centre the window
        //If the Screen not null
        try
        {
            if (Screen.PrimaryScreen != null)
            {
               finalTopPosition = 
                 (((double)Screen.PrimaryScreen.Bounds.Height / 2) - 
                  (windowHeight / 2));
            }
        }
        catch (Exception)
        {
        //If there was an error, just set the Final Positions to 0

           finalTopPosition = 0;
        }

    }
    string str = "window.open('" + url + "','','scrollbars=" + strShowScrollbars +
                                                ",menubar=" + strShowMenuBar +
                                                ",height=" + windowHeight +
                                                ",width=" + windowWidth +
                                                ",resizable=" + strIsResizable +
                                                ",toolbar=" + strShowToolbar +
                                                ",location=" + strHasLocation +
                                                ",status=" + strShowStatus +
                                                ",left=" + finalLeftPosition +
                                                ",top=" + finalTopPosition + "')";
    return str;
}

How I Use it

The code below is just to show where I put it in a GridView. As you can see, I put it in the OnClientClick area. I found this was where it worked best for me. I use it mainly for sending encrypted text to a page, but below, I have just used Google Video and Maps as an example.

As you can see, I have used -1 for Left position and -1 for Top position. This is how I can tell the code to try and centre the popup window in the screen.

If I send a location like 30 and 30, then it would be 30 pixels in and 30 pixels down from the top left corner of the screen.

ASP.NET
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" Visible="True"
              CellPadding="4" ForeColor="#333333" GridLines="None">
    <RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
    <Columns>
        <asp:TemplateField HeaderText="">
            <ItemTemplate>
                <asp:LinkButton ID="LbtnGoogle1" runat= "server" 
                OnClientClick='
                      <%#
                        CreatePopupUrl(  600 
                                       , 450
                                       , -1 //left position
                                       , -1 //top position
                                       , false
                                       , false
                                       , false
                                       , false
                                       , false
                                       , false
                                       , "http://www.google.com/{0}"
                                       , "video"
                                       ) 
                      %>'>Google Video</asp:LinkButton>
 
            </ItemTemplate>
        </asp:TemplateField>
       <asp:TemplateField HeaderText="">
            <ItemTemplate>
                <asp:LinkButton ID="LbtnGoogle2" runat= "server" 
                OnClientClick='
                      <%# 
                         CreatePopupUrl( 600
                                       , 450
                                       , 30 // left position
                                       , 30 // top position
                                       , false
                                       , false
                                       , false
                                       , false
                                       , false
                                       , false
                                       , "http://www.google.com/{0}"
                                       , "maps") 
                      %>'>Google Maps</asp:LinkButton>
 
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>

I hope that someone will find this helpful.

History

  • 15th October, 2009: Initial post
  • 16th October, 2009: Added source code
  • 19th October, 2009: Updated source code

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
United Kingdom United Kingdom
My first memories of programming were back in the days of Amstrad 464+, and we used to get a magazine called "Amstrad Action", every issue had some games or programs you could code into the computer and I used to love doing this.

I remember watching "War Games" at the same time as typing in the code to a small game on the computer, and thought it would be amazing to be able to connect the computer to the telephone!

In 2000, I started a computing A Level, part of the course was Delphi Programming, and I remember writing an application to display train time tables and ticket costs, and creating a manual of how to use it, and the lecturer said to me back then I would have a career as a Manual writer or a programmer. (I chose Programmer)

The programming lecturer was a lively, wacky lecturer, and that made it entertaining.

I then went back to night school in 2006 and learnt VB.NET.

This lecturer (at a different college, in a different country was also quite wacky and lively (seemed to be a common occurrence))

During the second year at night school my employer asked if I could put together a quotation application, I said I was up for it and the MD and I spent a day or two a week looking into the calculations, and after a few months we had created a quotation application that they still use to this day!
I created 4 more applications before joining my previous employer in 2008.

At my previous employment I created Mobile Software for Windows Mobile 6.1, Integrated with Sage Line 50, Exchequer, created ASP.NET websites, SSRS Reports for Customers and Internal use, created the UI for the new Scheduling application, and more.

Previously worked for Gemba Solutions Ltd as a Product Development Support Engineer.

Since 2016 I have been working for Currant Ltd, working with jQuery, ASP.NET and C#.

I also started volunteering at a CodeClub which I am enjoying.

Comments and Discussions

 
General[My vote of 1] Something missing Pin
Yves19-Oct-09 15:51
Yves19-Oct-09 15:51 
AnswerRe: [My vote of 1] Something missing Pin
Rob Branaghan19-Oct-09 22:33
Rob Branaghan19-Oct-09 22:33 
GeneralMy vote of 2 Pin
gaurav_verma_mca15-Oct-09 8:03
gaurav_verma_mca15-Oct-09 8:03 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.