Supress Postback on an ASP.NET ImageButton

If you are looking to suppress a postback on an imagebutton, then the following code should be helpful:

ASP.NET Image Button

Using MarkUp - Observe the onClientClick event


<asp:ImageButton ID="btnShow" ImageUrl="~/Images/Show.gif" 

runat="server" OnClientClick="return false;" />



Using Code Behind:

C#


    protected void Page_Load(object sender, EventArgs e)

    {

        btnShow.Attributes.Add("onclick", "return false;");

    }



VB.NET


    Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)

        btnShow.Attributes.Add("onclick", "return false;")

    End Sub



HTML Image Button

To prevent postback on an HTML Image button, use the following tag:


    <input type="image" id="imgBtn" 

    onclick="return false;" src="Images/Show.gif" />

MSDN RampUp - Learn something you can use right away!

What is RampUp!?

As quoted on the site
Ramp Up is a free, online, community-based learning program, with a number of different tracks that will help you build your portfolio of professional development skills. Ramp Up has a solid foundation of premium technical content from subject-matter gurus, and provides easy-to-access content in a variety of forms that guide you in learning the important skills. Join Ramp Up (it's free!) and help advance your career - click on a track now to start!

As of this writing, you have the following tracks currently available on the site:

SharePoint for Developers - Part 1
SharePoint for Developers - Part 2
Visual Studio 2008
For the VS 2002/2003 Developer: Learn VS 2005
For the VB 6.0 Developer: Learn VB 2005
For the Java Developer: Learn .NET
Developer Basics

You can access these track from over here MSDN RampUp

ASP.NET MVC 1.0 RC Available for download

ASP.NET MVC 1.0 RC was recently released by Microsoft and is available for download over here

If you are new to ASP.NET MVC, you can check a study guide by Stephen over here

ScottGu has a detailed post about the release over here

Clear TextBoxes from a Container control in Silverlight

If you have been looking out for a 'Clear Text' kinda funtionality in Silverlight, use this code. This code clear's the text of the TextBox and TextBlock kept in a container control like the Grid, Canvas or StackPanel.

C#


    private void btnClear_Click(object sender, RoutedEventArgs e)

    {

        foreach (object child in container.Children)

        { 

            if (child is TextBlock || child is TextBox)

                (child as TextBlock).Text = String.Empty;

        }

    }



VB.NET


    Private Sub btnClear_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)

        For Each child As Object In container.Children

            If TypeOf child Is TextBlock OrElse TypeOf child Is TextBox Then

                TryCast(child, TextBlock).Text = String.Empty

            End If

        Next child

    End Sub

Multiple Inheritance in C# and VB.NET

C# and VB.NET supports single inheritance, however they do support multiple 'interface' inheritance:

Here's a sample demonstrating the same:

C#


//Single Inheritance

 

public class A

{

    public A() { }

}

 

public class B : A

 

{

    public B() { }

}

 

 

 

//Multiple Interface Inheritance

 

interface IComparable

{

    int CompareTo(object obj);

}

 

interface ISomethingElse

{

    int EqualTo();

}

 

 

 

public class Z :  IComparable, ISomethingElse

{

    public int CompareTo(object obj)

    {

        // implementation code goes here 

    }

 

public int EqualTo()

    {

        // implementation code goes here 

    }

 

}



VB.NET


'Single Inheritance

 

Public Class A

    Public Sub New()

    End Sub

End Class

 

Public Class B

    Inherits A

 

    Public Sub New()

    End Sub

End Class

 

 

 

'Multiple Interface Inheritance

 

Friend Interface IComparable

    Function CompareTo(ByVal obj As Object) As Integer

End Interface

 

Friend Interface ISomethingElse

    Function EqualTo() As Integer

End Interface

 

 

 

Public Class Z

    Implements IComparable, ISomethingElse

    Public Function CompareTo(ByVal obj As Object) _
     As Integer Implements IComparable.CompareTo

        ' implementation code goes here 

    End Function

 

    Public Function EqualTo() As Integer Implements _
       ISomethingElse.EqualTo

        ' implementation code goes here 

    End Function

 

End Class

Convert String to Base64 and Base64 to String

System.Text.Encoding class provides methods to convert String to Base64 and vice-versa.

Convert String to Base64

First convert the string to a byte array and then use the Convert.ToBase64String() method to convert the byte array to a Base64 string.

C#


    byte[] byt = System.Text.Encoding.UTF8.GetBytes(strOriginal);

    // convert the byte array to a Base64 string

    strModified = Convert.ToBase64String(byt);



VB.NET


    Dim byt As Byte() = System.Text.Encoding.UTF8.GetBytes(strOriginal)

    ' convert the byte array to a Base64 string

    strModified = Convert.ToBase64String(byt)




Convert Base64 string to String

In order to convert a Base64 string back to the original string, use FromBase64String(). First FromBase64String() converts the string to a byte array and then use the relevant Encoding method to convert the byte array to a string, in our case UTF8.GetString();

C#


    byte[] b = Convert.FromBase64String(strModified);

    strOriginal = System.Text.Encoding.UTF8.GetString(b);



VB.NET


    Dim b As Byte() = Convert.FromBase64String(strModified)

    strOriginal = System.Text.Encoding.UTF8.GetString(b)




Convert Byte[] (Byte Array) to String and ViceVersa

The Encoding.GetBytes() method contains six overloads to encode all the characters into a sequence of bytes.

Convert Byte[]( Byte Array) to String

Here 'b' is the byte array

C#


    string strModified = System.Text.Encoding.Unicode.GetString(b);



VB.NET


    Dim strModified As String = System.Text.Encoding.Unicode.GetString(b)




Convert a String to Byte[] (Byte Array)

C#


    byte[] b = Encoding.Unicode.GetBytes(strOriginal);



VB.NET


    Dim b As Byte() = Encoding.Unicode.GetBytes(strOriginal)

Test jQuery and jQueryUI code online - by Google

If you have been looking out to execute jQuery or jQueryUI code online, then here's a brand new tool from google. Check out AJAX API Playground

This new tool released by google will make it easier to test your Google Javascript API code. The newly launched Google's AJAX API Playground provides one such interface.

Here's a screenshot of this tool in action



You can access this tool from here AJAX API Playground

jQuery 1.3.1 released with Fixes

A few days ago, I had blogged about the new release of jQuery 1.3 over here http://www.devcurry.com/2009/01/jquery-13-released-jquery-13.html

The jQuery team has now promptly come out with a 'bug-fix' jQuery 1.3.1 release. This release mainly fixes browser compatibility issues.

You can download this new release from here jQuery 1.3.1. Some additional info about the release can be read from here

Update: jQuery 1.3.2 along with Visual Studio 2008 has been released http://www.devcurry.com/2009/02/jquery-132-intellisense-for-visual.html

Quickly Replace Non-Numeric characters In a String

If you have a requirement where in you do not want to prevent users from entering non-numeric characters in a textbox, however want to filter out all the non-numeric characters, then here's how to do so:

First import the namespace System.Text.RegularExpressions;

C#


    // Replace non-numeric characters 

    string str = "12d223*23#22";

    string newStr = Regex.Replace(str, @"[^\d]", "");

 

    // Displays 122232322



VB.NET


    ' Replace non-numeric characters 

    Dim str As String = "12d223*23#22"

    Dim newStr As String = Regex.Replace(Str, "[^\d]", "")

 

    ' Displays 122232322

jQuery articles on dotnetcurry.com

A user today posted a request to help him understand how jQuery works with ASP.NET. If you are looking out for similar info, I have published some ASP.NET jQuery articles at dotnetcurry.com

Check out the beginner's guide Using jQuery with ASP.NET - A Beginner's Guide

To see how jQuery can be used with ASP.NET controls, check jQuery and ASP.NET

Remove Duplicate Items from a Generic List

If you have a List<string> and want to remove duplicate values before binding it to a control, here's how to do so

C#


var strList = new List<string> 

{ "Jane", "Bill", "jane", "carol", "Carol", "bill" }; 

strList = strList.ConvertAll(low => low.ToLowerInvariant());

 

var result = from str in strList

        group str by str into grp

        select new { Text = grp.Key};

foreach (var res in result)

{

    DropDownList1.Items.Add(res.Text);

}



VB.NET


    Dim strList = New List(Of String)(New String() _

                {"Jane", "Bill", "jane", "carol", "Carol", "bill"})

    strList = strList.ConvertAll _

    (Function(low) low.ToLowerInvariant())

 

    Dim result = _

     From str In strList _

     Group str By str Into grp = Group _

     Select New With {Key .Text = str}

    For Each res In result

        DropDownList1.Items.Add(res.Text)

    Next res

Export GridView to Excel

Users often post a requirement to export the data in an ASP.NET GridView to Excel. Here's a simple way to do so:

C#


protected void Button1_Click(object sender, EventArgs e)

{

    Response.AddHeader("content-disposition", 
       "attachment;filename=FileName.xls");

    Response.Charset = String.Empty;

    Response.ContentType = "application/vnd.xls";

    System.IO.StringWriter sw = new System.IO.StringWriter();

    System.Web.UI.HtmlTextWriter hw = new HtmlTextWriter(sw);

    GridView1.RenderControl(hw);

    Response.Write(sw.ToString());

    Response.End();

}



VB.NET


    Protected Sub Button1_Click(ByVal sender As Object, _
     ByVal e As EventArgs)

        Response.AddHeader("content-disposition", _
         "attachment;filename=FileName.xls")

        Response.Charset = String.Empty

        Response.ContentType = "application/vnd.xls"

        Dim sw As System.IO.StringWriter = _
          New System.IO.StringWriter()

        Dim hw As System.Web.UI.HtmlTextWriter = _
            New HtmlTextWriter(sw)

        GridView1.RenderControl(hw)

        Response.Write(sw.ToString())

        Response.End()

    End Sub



To read about some more tips and tricks about the GridView, check GridView Tips and Tricks using ASP.NET 2.0

Execute JavaScript function from ASP.NET codebehind

Calling a JavaScript function from codebehind is quiet simple, yet it confuses a lot of developers. Here's how to do it. Declare a JavaScript function in your code as shown below:

JavaScript

<head runat="server">
<
title>Call JavaScript From CodeBehind</title>
<
script type="text/javascript">
function
alertMe() {
alert('Hello');
}
</script>
</
head>

In order to call it from code behind, use the following code in your Page_Load

C#

protected void Page_Load(object sender, EventArgs e)
{
if (!ClientScript.IsStartupScriptRegistered("alert"))
{
Page.ClientScript.RegisterStartupScript(this.GetType(),
"alert", "alertMe();", true);
}
}

VB.NET

If (Not ClientScript.IsStartupScriptRegistered("alert")) Then
Page.ClientScript.RegisterStartupScript _
(Me.GetType(), "alert", "alertMe();", True)
End If

The Page.ClientScript.RegisterStartupScript() allows you to emit client-side script blocks from code behind. More info here http://msdn.microsoft.com/en-us/library/system.web.ui.clientscriptmanager.registerstartupscript.aspx

To call the JavaScript code on a button click, you can add the following code in the Page_Load

btnCall.Attributes.Add("onclick", " return alertMe();");

Update: This was a very simple example. However comments left by previous users suggest that they want more than this :) If you want to go into details, here are two articles I wrote and strongly recommend

Calling JavaScript from ASP.NET Master Page and Content Pages - Part I

Calling JavaScript from ASP.NET Master Page and Content Pages - Part II

Open a PopUp Window on the ASP.NET Button Click event and pass Parameters

A User asked me how to Open a PopUp window when the user clicks on an ASP.NET Button Server Control. He also wanted to pass parameters to the url. Here's how it is done:

C#


protected void Button1_Click(object sender, EventArgs e)

{

    string queryString = 

        "http://localhost:39208/TreeView.aspx?param1=" 

        + TextBox1.Text.Trim();   

    string newWin = 

        "window.open('" + queryString + "');";

    ClientScript.RegisterStartupScript

        (this.GetType(), "pop", newWin, true);

}



VB.NET


    Protected Sub Button1_Click(ByVal sender As Object, _

                                ByVal e As EventArgs)

        Dim queryString As String = _

           "http://localhost:39208/TreeView.aspx?param1=" & _

            TextBox1.Text.Trim()

        Dim newWin As String = _

           "window.open('" & queryString & "');"

        ClientScript.RegisterStartupScript(Me.GetType(), _

                                       "pop", newWin, True)

    End Sub

jQuery 1.3 released + jQuery 1.3 intellisense for VS 2008

A new version of jQuery 1.3 was released by John Resig and his team. This is a major release with animation enhancements, performance improvements and much more. You can find the release notes over here jQuery 1.3 Release Notes

jQuery 1.3 can be downloaded from over here: Download Query 1.3

jQuery Intellisense with Visual Studio 2008

If you are new to jQuery intellisense in Visual Studio 2008, check one of my posts at dotnetcurry, Using jQuery with ASP.NET - A Beginner's Guide where I have covered it step by step.


Unfortunately the 1.2.6 VS 2008 intellisense documentation file does not work properly with jQuery 1.3. In order to use a intellisense documentation for jQuery 1.3, check James blog where he

Extract Individual Contents of the Connection String from your Web.Config

A lot of blogs speak about retrieving ConnectionStrings from your web.config files. However what if we need to extract individual contents/portions like the DataSource or the Initial Catalog from the Connection String. This post explains how to extract them

C#


protected void Page_Load(object sender, EventArgs e)

{

string connStr = WebConfigurationManager.ConnectionStrings

    ["NorthwindConnectionString"].ConnectionString;

SqlConnectionStringBuilder bldr = 

    new SqlConnectionStringBuilder(connStr);

// displays (local)

string dataSrc = bldr.DataSource;

// displays Northwind

string iniCat = bldr.InitialCatalog;

}



VB.NET


    Protected Sub Page_Load(ByVal sender As Object, _

                            ByVal e As EventArgs)

        Dim connStr As String = _

        WebConfigurationManager.ConnectionStrings _

        ("NorthwindConnectionString").ConnectionString

        Dim bldr As New SqlConnectionStringBuilder(connStr)

        ' displays (local)

        Dim dataSrc As String = bldr.DataSource

        ' displays Northwind

        Dim iniCat As String = bldr.InitialCatalog

    End Sub



As shown above, we use the SqlConnectionStringBuilder to extract the contents of a connection string. This class provides a simple way to create and manage contents of the ConnectionString.

ASP.NET TreeView - Keep only one parent node expanded

A user recently asked me on the ASP.NET forums on how to expand only one parent node at a time. When the user clicks on a parent node, the ones that are already expanded (if any) should collapse. The answer to this question lies in the TreeNodeExpanded event as shown below:

TreeView markup


<asp:TreeView ID="TreeView1" runat="server" 

    ExpandDepth = "0" 

    ontreenodeexpanded="TreeView1_TreeNodeExpanded">

 <Nodes>

  <asp:TreeNode Text="Managers">

    <asp:TreeNode Text="Scott" Value="EID-XY34E" />

    <asp:TreeNode Text="Brinda" Value="EID-34D78" />

    <asp:TreeNode Text="Kathy" Value="EID-563D1" />

  </asp:TreeNode>

  <asp:TreeNode Text="Accounts">

    <asp:TreeNode Text="Laura" Value="EID-QQ21E" />

    <asp:TreeNode Text="Jemmica" Value="EID-YUR78" />

    <asp:TreeNode Text="Nicole" Value="EID-TG331" />

  </asp:TreeNode>

  <asp:TreeNode Text="Admin">

    <asp:TreeNode Text="Jack" Value="EID-PO41E" />

    <asp:TreeNode Text="Victor" Value="EID-HYR78" />

    <asp:TreeNode Text="Broady" Value="EID-KL931" />

  </asp:TreeNode>

</Nodes>

</asp:TreeView>



C#


protected void TreeView1_TreeNodeExpanded(object sender, 

    TreeNodeEventArgs e)

{

    string currValue = e.Node.Value.Trim();

    foreach (TreeNode tnode in TreeView1.Nodes)

    {

        if (tnode.Value != currValue)

        {

            tnode.Collapse();

        }

    }

}



VB.NET


    Protected Sub TreeView1_TreeNodeExpanded( _

    ByVal sender As Object, ByVal e As TreeNodeEventArgs)

        Dim currValue As String = e.Node.Value.Trim()

        For Each tnode As TreeNode In TreeView1.Nodes

            If tnode.Value <> currValue Then

                tnode.Collapse()

            End If

        Next tnode

    End Sub

Easiest way to Convert List to Lower case using LINQ

A user recently asked me a question. He had a List<string> collection that he obtained from a service. He wanted to convert the strings in the List<string> into lower case and then bind it to an ASP.NET DropDownList. He asked me for the simplest way to do so. Here's the solution I suggested him using LINQ:

C#


// Convert to Lower case and bind to dropdownlist

List<string> strList = new List<string> 

{ "One", "TWO", "THree", "Four", "five" };        

strList = strList.ConvertAll(low => low.ToLowerInvariant());

foreach (string s in strList)

{

    DropDownList1.Items.Add(s);

}



VB.NET


        Dim strList As List(Of String) = _

        New List(Of String)(New String() _

                    {"One", "TWO", "THree", "Four", "five"})

        strList = strList.ConvertAll(Function(low)_
        low.ToLowerInvariant())

        For Each s As String In strList

            DropDownList1.Items.Add(s)

        Next s

Dynamically Create a DIV tag using Server-Side code or JavaScript

A user recently sent across a request where he needed to create HTML tags dynamically. Depending on the need, you may use server side code or plain JavaScript. This sample shows how to create a <DIV> tag dynamically using JavaScript or ASP.NET

Create a DIV Tag using JavaScript
<html xmlns="http://www.w3.org/1999/xhtml">

<
head>

<
title>Create DIV Dynamically Using JavaScript</title>

<
script type="text/javascript" language="javascript">

function
DynamicDiv() {
var dynDiv = document.createElement("div");
dynDiv.id = "divDyna";
dynDiv.innerHTML = "Created using JavaScript";
dynDiv.style.height = "20px";
dynDiv.style.width = "300px";
dynDiv.style.backgroundColor = 'gray';
document.body.appendChild(dynDiv);
}

</script>
</
head>

<
body>
<
div>
<
input id="Button1" type="button"
value="Using JS" onclick="DynamicDiv();" />

</
div>
</
body>

</
html>
Create a DIV Tag using ASP.NET
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default5.aspx.cs"
Inherits="Default5" %>

<!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="head1" runat="server">
<
title>Create DIV Dynamically Using ASP.NET</title>
</
head>

<
body>
<
form id="form1" runat="server">
<
div>
<
asp:Button ID="btnCode" runat="server"
onclick="btnCode_Click"
Text="Code Behind" />
</
div>
</
form>
</
body>

</
html>



C#

protected void btnCode_Click(object sender, EventArgs e)
{
System.Web.UI.HtmlControls.HtmlGenericControl dynDiv =
new System.Web.UI.HtmlControls.HtmlGenericControl("DIV");
dynDiv.ID = "dynDivCode";
dynDiv.Style.Add(HtmlTextWriterStyle.BackgroundColor, "Gray");
dynDiv.Style.Add(HtmlTextWriterStyle.Height, "20px");
dynDiv.Style.Add(HtmlTextWriterStyle.Width, "300px");
dynDiv.InnerHtml = "I was created using Code Behind";
this.Controls.Add(dynDiv);
}

VB.NET

Protected Sub btnCode_Click(ByVal sender As Object, ByVal e As EventArgs)
Dim dynDiv As New System.Web.UI.HtmlControls.HtmlGenericControl("DIV")
dynDiv.ID = "dynDivCode"
dynDiv.Style.Add(HtmlTextWriterStyle.BackgroundColor, "Gray")
dynDiv.Style.Add(HtmlTextWriterStyle.Height, "20px")
dynDiv.Style.Add(HtmlTextWriterStyle.Width, "300px")
dynDiv.InnerHtml = "I was created using Code Behind"
Me.Controls.Add(dynDiv)
End Sub

Similarly you can also check

How to add CSS Programmatically to an ASP.NET Page

How to add Control dynamically in an ASP.NET AJAX application

Toggle Ordered/ Unordered List Using jQuery

So let us say you have a tree like structure created with a bunch of <ul> and <li>. Now you come across a requirement where you need to expand and collapse these sections. Let us see how to do this using jQuery (tested on IE and Firefox)


<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

    <title></title>    

    <style type="text/css">

        .clsUL

        {            

            cursor:hand;

        }

    </style>

    <script src="Scripts/jquery-1.2.6.js" type="text/javascript">

    </script>

 

    <script type="text/javascript"> 

        $(document).ready(function(){

        $('#unord li').click(function() { 

                    $(this).children('ul').slideToggle("slow"); 

            }); 

        });

    </script>

 

</head>

 

<body>

    <form id="form1" runat="server">

    <div>

    <ul id="unord" class="clsUL"> 

        <li>Client-Side Languages

            <ul>

                <li>

                    jQuery

                </li>

                <li>

                    JavaScript

                </li>

                <li>

                    JScript

                </li>

            </ul>

        </li>

        <li>Server-Side Languages

            <ul>

                <li>

                    C#

                </li>

                <li>

                    VB.NET

                </li>

                <li>

                    Others

                </li>

            </ul>

        </li>

    </ul>   

    </div>

    </form>

</body>

</html>



The code shown above, collapses and expands the section of <li> kept inside <ul>. Needless to say, jQuery rocks!

Windows 7 Beta Available for Download

On Jan 7, 2009 Microsoft CEO Steve Ballmer announced the availability of the Windows 7 Beta operating system in the International Consumer Electronics Show (CES).

Also announced during the show was the latest version of the Windows Live.

Ballmer was quoted saying
Windows 7 and Windows Live are part of an incredible pipeline of consumer technology that is making it easier than ever for people to communicate, share and get more done.


Check out the new features of Windows 7 over here Windows 7 What's New

The Beta can be downloaded from here Download Windows 7 Beta

Free Book - Patterns & Practices Application Architecture Guide 2.0

The Application Architecture Guide 2.0 provides design-level guidance for the architecture and design of applications built on the .NET Framework.

The guide talks about the Fundamentals of Application Architecture and proposes Design Guidelines. It also discusses design and deployment patterns along with some cool guidelines while designing a layered approach.

Also check out the common type of architecture types(Web, Windows, Mobile) and their key design characteristics. There are also some cheat sheets at the end.

Overall, a 'must-read' guide if you plan to architect solutions around .NET

Download the Application Architecture Guide 2.0

Add CSS to Ordered and Unordered List using jQuery

I was working on a solution where I had to add CSS to a bunch of <li> inside <ul>. I used jQuery to do in the following manner:

<html xmlns="http://www.w3.org/1999/xhtml">
<
head>
<
title></title>
<
style type="text/css">
.clsLI
{
color:Gray;
cursor:pointer;
}
</style>
<
script src="http://code.jquery.com/jquery-latest.js"
type="text/javascript"></script>


<
script type="text/javascript">
$(document).ready(function() {
$("ul#unord li").hover(
function() {
$(this).addClass("clsLI");
},
function() {
$(this).removeClass("clsLI");
}
)
});
</script>
</
head>

<
body>
<
form id="form1">
<
div>
<
ul id="unord">
<
li>
jQuery
</li>
<
li>
JavaScript
</li>
<
li>
jQuery and JavaScript
</li>
</
ul>
</
div>
</
form>
</
body>
</
html>

In the code above, the CSS gets applied when the user hovers the mouse on a <li>. In this example, we hover the mouse over 'JavaScript'. The output is as shown below:


Display a Counter before Redirecting Users

A lot of sites display a counter before redirecting a user. Let us see how to create this counter using JavaScript. The solution has been tested in IE7 and Firefox.


<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

    <title>Redirect Users</title>

    <script type="text/javascript" language="javascript">

        window.onload = function() 

        {

            Redirect();

        }

 

        var cnt = 10;

        function Redirect()

        {                        

            if (cnt > 0){

                document.getElementById("cntDisp").innerHTML = 

                cnt + " seconds left..";                

                cnt = cnt - 1;

                setTimeout("Redirect()", 1000);

            }

            else {

                document.getElementById("cntDisp").innerHTML =

                "redirecting...";

                window.open("http://www.dotnetcurry.com/", "_self");

            }

        }        

    </script>

</head>

    <body>

        <div id="cntDisp"/>    

    </body>

</html>



The code displays a counter for 10 seconds and then redirects the user to the desired url. The same code cab be used on an ASP.NET Page.

Alert/Prevent Users From closing the browser

Here's a simple script that works on both IE and Mozilla and displays a confirmation box before closing the browser. You can use this script to detect if an activity is on and alert users about the same, before they close the browser.


<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

    <title></title>

    <script type="text/javascript"> 

        window.onbeforeunload = function(e) {

            e = e || window.event;

            e.returnValue = "Your message here";

        };

    </script>

</head>

<body>

    <form id="form1" runat="server">

    <div>

 

    </div>

    </form>

</body>

</html>



You can use the same script on ASP.NET pages too