Wednesday, August 10, 2011

How to insert or add URL links inside the gridview?

There are many ways to insert or add links inside a grid. There are many ways to display all the pages in your site in a gridview.
This is one way,
<asp:HyperLinkField DataTextField="Modules" HeaderText="Name" NavigateUrl='<% Bind("URL") %>' />

This the second way to do this,
                                                                    <asp:TemplateField HeaderText="Name" SortExpression="Modules">
                                                                        <ItemTemplate>
                                                                            <asp:HyperLink ID="hlModules" runat="server" Text='<%# Bind("Modules") %>' />
                                                                        </ItemTemplate>
                                                                    </asp:TemplateField>

Then add this code in gridview RowCreated event,

if (e.Row.RowType == DataControlRowType.DataRow)
{
    HyperLink hl = (HyperLink)e.Row.FindControl("hlModules");
    hl.NavigateUrl = "MyPage.aspx";
}

But if you want to open the page in a new window or pop up. You need to put this code in RowDataBound event of the gridview and do like this,
           

if (e.Row.RowType == DataControlRowType.DataRow)
{
HyperLink hl = (HyperLink)e.Row.FindControl("hlModules");
      switch(hl.Text)
      {
            case "FirstPage":
                  hl.NavigateUrl = "javascript:OpenFirstPage();";
            break;                       
            case "SecondPage":
                  hl.NavigateUrl = "javascript:OpenSecondPage();";
            break;                       
 
      }
}

Of course you need to create the javascript to open a pop up window like this,

<script type="text/javascript" language="javascript">
var winArray = new Array()
function OpenFirstPage()
{
if (!winArray[0] || winArray[0].closed)
      winArray[0] = window.open("FirstPage.aspx", "FirstPage", "width=800,height=600,toolbar=no, menubar=no, directories=no, resizable=yes, scrollbars=yes");
else
            winArray[0].focus();
}
function OpenSecondPage()
{
if (!winArray[0] || winArray[0].closed)
      winArray[0] = window.open("SecondPage.aspx", "SecondPage", "width=800,height=600,toolbar=no, menubar=no, directories=no, resizable=yes, scrollbars=yes");
else
            winArray[0].focus();
}
</script>

You may refer to my other post or blog on how to open popup or close all popup windows.

No comments:

Post a Comment