Load pages in DIV using JQuery

If you have a <DIV> in your HTML or ASP.NET page and want to load another page in that DIV, then here's how to do so using one line of jQuery code


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


<head runat="server">


    <title></title>


    <style type="text/css">


    .divPage


    {


        width:300px;


        height:200px;


    }


    </style>


 


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


    <script type="text/javascript">


        $(document).ready(function() {


        $('#LoadPage').load('Default.aspx');


        });    


    </script>


</head>


<body>


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


    <div>


    <div id="LoadPage" class="divPage">


    </div>


    </div>


    </form>


</body>


</html>


Can my class be serialized?

A common question asked is how do you determine if a class can be serialized? My answer is - serialize the class and then determine.

A common misconception is that if the class has the [Serializable] attribute, it can be serialized. This may or may not be the case. If any one of the fields in the class cannot be serialized, the serialization of the class fails.

If you would like to programmatically determine if a class can probably be serialized, use the following code. The code determines if the class Employee can be serialized or not:

C#


        Employee emp = new Employee();


        if (emp.GetType().IsSerializable)


        {


            Response.Write(emp.GetType().ToString() + " can probably be serialized");


        }


        else


        {


            Response.Write(emp.GetType().ToString() + " cannot be serialized");


        }




VB.NET


Dim emp As New Employee()


If emp.GetType().IsSerializable Then


    Response.Write(emp.GetType().ToString() & " can probably be serialized")


Else


    Response.Write(emp.GetType().ToString() & " cannot be serialized")


End If


Get your daily dose of Technology!

Have you been looking out for a Community based site where like-minded developers like you post links to the articles written by them or others? Here are 3 amazing sites which showcase stories submitted by users like you

www.dotnetkicks.com - DotNetKicks.com is a community based news site edited by our members. It specialises in .NET development techniques, technologies and tools including ASP.NET, C#, VB.NET, C++, Visual Studio, SubSonic, Open Source, SQL Server, Silverlight & Mono.

Individual users of the site submit and review stories, the most popular of which make it to the homepage. Users are encouraged to 'kick' stories that they would like to appear on the homepage. If a story receives enough kicks, it will be promoted.

www.dzone.com - Dzone is a free link-sharing community for developers. Anyone can submit new links to the incoming queue. Members vote on upcoming links to determine what gets promoted. Everyone can browse, search and comment on links

www.dotnetshoutout.com - DotNetShoutout is a place where you can find the latest Microsoft .NET stories to increase your skills and share your opinions.

Using JavaScript to DropDown an HTML Select on MouseOver

An HTML SELECT can be programmatically dropdown on MouseOver using JavaScript. On MouseOut, we can get the SELECT to its default positions. Here's how to do it

<html xmlns="http://www.w3.org/1999/xhtml">
<
head>
<
title>Drop on Hover</title>
<
script type="text/javascript">
function
DropList() {
var n = document.getElementById("sel").options.length;
document.getElementById("sel").size = n;
}
</script>
</
head>
<
body>
<
div>
<
select id="sel" onmouseover="DropList()" onmouseout="this.size=1;">
<
option>One</option>
<
option>Two</option>
<
option>Three</option>
<
option>Four</option>
<
option>Five</option>
<
option>Six</option>
<
option>Seven</option>
<
option>Eight</option>
</
select>
</
div>
</
body>
</
html>

See a Live Demo.

image

On Mouse Hover

image

Saturdays go missing in the ASP.NET AJAX Calendar Extender

In the ASP.NET forums, I have seen many users complaining about the calendar display while using the ASP.NET AJAX CalendarExtender. The issue was particularly found in IE7 where Saturdays were not displayed in the calendar.

A simple solution that I had adopted sometime back was to set the padding and margin of the CalendarExtender to 0px;

The solution is shown over here:


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


<head runat="server">


    <title></title>


    <style type="text/css">


    .calFixIE *


    {


        padding:0px;


        margin:0px;


    }


    </style>


</head>


<body>


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


    <div>


        <asp:ScriptManager ID="ScriptManager1" runat="server">


        </asp:ScriptManager>


        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>


        <cc1:CalendarExtender ID="CalendarExtender1" TargetControlID="TextBox1"


        Format="dd/MM/yyyy" runat="server">


        </cc1:CalendarExtender>       


    </div>   


    </form>


</body>


</html>


How to Split a String using LINQ and Handle Empty Strings

While splitting strings using a delimiter, it's important to consider empty strings. A user recently mailed me with this requirement and he wanted to do it using LINQ. Here's a code sample I borrowed from cccook which shows how to do so:

C#


    protected void Page_Load(object sender, EventArgs e)


    {


        string str = "Are;You;A;Regular;Visitor;;DevCurry.com;?";


        Regex.Split(str, ";", RegexOptions.ExplicitCapture)


            .Where(s => !String.IsNullOrEmpty(s))


            .ToList()


            .ForEach(s => Response.Write(s+"\n"));


    }




VB.NET


 


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


    Dim str As String = "Are;You;A;Regular;Visitor;;DevCurry.com;?"


    Regex.Split(str, ";", RegexOptions.ExplicitCapture).Where(Function(s) (Not String.IsNullOrEmpty(s))).ToList().ForEach(Function(s) Response.Write(s + Constants.vbLf))


End Sub


Microsoft Expression Web Articles, Tips and Tricks

If you have been working on Microsoft Expression Web and often look out for good technical resources,articles, tips and tricks on the same, then check out http://saffronstroke.com/expression-web-tips/ and http://www.dotnetcurry.com/BrowseArticles.aspx?CatID=48. These tips are written by Minal Agarwal, a enthusiastic Expression Web user, who shares her experiences with the tool through these sites.

Microsoft Expression Web Trial version can be downloaded from here

Get the Client ID of an ASP.NET Control in jQuery

While navigating the DOM using jQuery, it is often necessary to get the id of the control and perform operations on it, like hiding the control.

However, if you are using an ASP.NET Master Page and would like to retrieve the ClientId of a control using jQuery, then here's how to do so:


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


<head runat="server">


<title></title>


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


<script type="text/javascript">


    $(document).ready(function() {


        $("#<%=RadioButtonList1.ClientID %>").hide('slow');


    });    


</script>


</head>


<body>


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


<div>   


<asp:RadioButtonList ID="RadioButtonList1"  runat="server">


<asp:ListItem Value="Ten"></asp:ListItem>


<asp:ListItem Value="Twenty"></asp:ListItem>


<asp:ListItem Value="Thirty"></asp:ListItem>


<asp:ListItem Value="Forty"></asp:ListItem>


</asp:RadioButtonList>




The example shown above fetches the ClientId of the RadioButtonList and hides it using jQuery

Referencing a .js (JavaScript) file from ASP.NET Content Page

I have seen developers adding a JavaScript reference to the Master Pages and then using the JavaScript functions in Content Pages. However, with this approach, the JavaScript is referenced in each page of the application using that MasterPage as its template. If you want to reference the JavaScript file only on one ContentPage, then here's how to do so:

C#


protected void Page_Load(object sender, EventArgs e)


{


    Page.ClientScript.RegisterClientScriptInclude("onlyone", ResolveUrl(@"Scripts\SomeScript.js"));


    if (!Master.Page.ClientScript.IsStartupScriptRegistered("MS"))


    {


        Master.Page.ClientScript.RegisterStartupScript


            (this.GetType(), "MS", "SomeMethodJS();", true);


    }


}




VB.NET


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


    Page.ClientScript.RegisterClientScriptInclude("onlyone", ResolveUrl("Scripts\SomeScript.js"))


    If (Not Master.Page.ClientScript.IsStartupScriptRegistered("MS")) Then


        Master.Page.ClientScript.RegisterStartupScript(Me.GetType(), "MS", "SomeMethodJS();", True)


    End If


End Sub


Are you attending Tech.Ed-India 2009?

We are all excited about Tech.Ed-India 2009 to be held in Hyderabad from May 13-15. New Technology Innovations, Trends, Deep Down Sessions, MS Product Team Interaction, Hands on Training and what not, you will find plenty of rocking stuff! Most of all, see the very energetic Steve Ballmer LIVE at TechEd, Hyderabad.

You can Register for the event over here

Get more info over here http://www.microsoft.com/india/teched2009/

I have planned to invest my time and money! Have you?

ASP.NET MVC Unleashed and Free Resources

Stephen Walther has been posting some great stuff on ASP.NET MVC. Here are some stuff that you can download and read for free

FREE Chapters from ASP.NET MVC Unleashed Book - http://stephenwalther.com/blog/category/11.aspx

ASP.NET MVC Workshop Code - Entire Movie Database application in ASP.NET MVC with unit tests and a reasonably good design

Blog posts, Video and Tutorials - http://stephenwalther.com/blog/category/4.aspx

His blog is undoubtedly the No. 1 resource for ASP.NET MVC to keep you tuned!

Formatting Currency in ASP.NET

Formatting Currency in ASP.NET in most cases is a very easy to do task, however it baffles many. Users fail to understand the importance of Culture and UICulture as well as the difference between them.

The UICulture property determines the resource files loaded for a page. The Culture property determines how strings such as currency, dates etc are formatted. A culture name For eg: en-US consists of two parts. The first part(en) is the language code and the second part(US) is the country/region code. If you do not specify the country or region code, then you have specified something called a neutral culture.

You can set either the UICulture or Culture properties by using the <%@ Page %> directive or you can set these properties globally in the web configuration file as shown below:


  <globalization culture="en-GB" uiCulture="en-GB" />




Let's take a simple example where we will format a string to represent Great Britain's currency formatting

Add this to your page directive


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="TestArea6.aspx.cs"


Inherits="TestArea6" Culture="en-GB" %>




C#


protected void Page_Load(object sender, EventArgs e)


{


    decimal revenue = 1452.66m;


    string str = String.Format("{0:C}", revenue);


    Response.Write(str);


}




VB.NET


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


    Dim revenue As Decimal = 1452.66D


    Dim str As String = String.Format("{0:C}", revenue)


    Response.Write(str)


End Sub




Output: £1,452.66

Display Message On MouseOver In an ASP.NET GridView

To display a message in an ASP.NET GridView on MouseOver, handle the RowDataBound event. As given in MSDN,
The RowDataBound event is raised when a data row (represented by a GridViewRow object) is bound to data in the GridView control. This enables you to provide an event-handling method that performs a custom routine, such as modifying the values of the data bound to the row, whenever this event occurs.



    <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString %>"


        SelectCommand="SELECT [CustomerID], [CompanyName], [ContactName], [Address], [City] FROM [Customers]">


    </asp:SqlDataSource>


 


    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="CustomerID"


            DataSourceID="SqlDataSource1" AllowPaging="True" AllowSorting="True"


            OnRowDataBound="GridView1_RowDataBound">


            <Columns>                          


                <asp:BoundField DataField="CustomerID" HeaderText="CustomerID" ReadOnly="True" SortExpression="CustomerID" />


                <asp:BoundField DataField="CompanyName" HeaderText="CompanyName" SortExpression="CompanyName" />


                <asp:BoundField DataField="ContactName" HeaderText="ContactName" SortExpression="ContactName" />


                <asp:BoundField DataField="Address" HeaderText="Address" SortExpression="Address" />


                <asp:BoundField DataField="City" HeaderText="City" SortExpression="City" />


            </Columns>


     </asp:GridView>




C#


protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)


{


 if ( e.Row.RowType == DataControlRowType.DataRow )


 {


  e.Row.Attributes.Add("onmouseover", "alert('Display some message');");


 }


}




VB.NET


    Protected Sub GridView1_RowDataBound(ByVal sender As Object, ByVal e As GridViewRowEventArgs)


        If e.Row.RowType = DataControlRowType.DataRow Then


            e.Row.Attributes.Add("onmouseover", "alert('Display some message');")


        End If


    End Sub


How to Bind an ASP.NET DropDownList to an Enumeration with two lines of code

I have seen users writing number of lines of code to do a simple thing as binding an Enumeration to an ASP.NET DropDownList or ListBox. Here's how to do this with just two lines of code

<asp:DropDownList ID="DropDownList1" runat="server">
</
asp:DropDownList>

<
asp:ListBox ID="ListBox1" runat="server"></asp:ListBox>

C#

enum Speed
{
Low = 1,
Medium = 2,
High = 3
}
protected void Page_Load(object sender, EventArgs e)
{
DropDownList1.DataSource = Enum.GetValues(typeof(Speed));
DropDownList1.DataBind();

ListBox1.DataSource = Enum.GetValues(typeof(Speed));
ListBox1.DataBind();
}

VB.NET

Friend Enum Speed
Low = 1
Medium = 2
High = 3
End Enum

Protected Sub
Page_Load(ByVal sender As Object, ByVal e As EventArgs)
DropDownList1.DataSource = System.Enum.GetValues(GetType(Speed))
DropDownList1.DataBind()

ListBox1.DataSource = System.Enum.GetValues(GetType(Speed))
ListBox1.DataBind()
End Sub

OUTPUT

image

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

Most of us know how to create controls dynamically in an ASP.NET application. However a lot of users get confused while creating controls dynamically in an ASP.NET AJAX application. This is as the there is an async postback involved. Here's a very common technique to create controls dynamically in an ASP.NET AJAX application using ViewState


<body>


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


    <div>


    <asp:ScriptManager ID="ScriptManager1" runat="server">


    </asp:ScriptManager>


    <asp:UpdatePanel ID="UpdatePanel1" runat="server">


    <ContentTemplate>


           <asp:Button ID="Button1" runat="server" Text="Create TextBoxes" onclick="Button1_Click" />


   </ContentTemplate>


   </asp:UpdatePanel>


    </div>


    </form>


</body>




C#


    protected void Button1_Click(object sender, EventArgs e)


    {


        int cnt = 0;


 


        if (ViewState["txtBoxes"] != null)


            cnt = (int)ViewState["txtBoxes"];


 


        cnt = cnt + 1;


        ViewState["txtBoxes"] = cnt;


 


 


        for (int i = 0; i < cnt; i++)


        {


            TextBox tb = new TextBox();


            tb.Text = "";


            tb.ID = "TextBox" + cnt;


            UpdatePanel1.ContentTemplateContainer.Controls.Add(tb);


        }    


    }




VB.NET


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


        Dim cnt As Integer = 0


 


        If ViewState("txtBoxes") IsNot Nothing Then


            cnt = CInt(Fix(ViewState("txtBoxes")))


        End If


 


        cnt = cnt + 1


        ViewState("txtBoxes") = cnt


 


 


        For i As Integer = 0 To cnt - 1


            Dim tb As New TextBox()


            tb.Text = ""


            tb.ID = "TextBox" & cnt


            UpdatePanel1.ContentTemplateContainer.Controls.Add(tb)


        Next i


    End Sub


Display the First and Last Day of Week In ASP.NET

Use the DateTime class to display the First Day and Last of the Week. Here's how

C#


DateTime dt = DateTime.Now;


DateTime wkStDt = DateTime.MinValue;


DateTime wkEndDt = DateTime.MinValue;


wkStDt = dt.AddDays(1 - Convert.ToDouble(dt.DayOfWeek));


wkEndDt = dt.AddDays(7 - Convert.ToDouble(dt.DayOfWeek));


Response.Write(wkStDt.ToString("MMMM-dd") + "<br/>");


Response.Write(wkEndDt.ToString("MMMM-dd"));




VB.NET


Dim dt As DateTime = DateTime.Now


Dim wkStDt As DateTime = DateTime.MinValue


Dim wkEndDt As DateTime = DateTime.MinValue


wkStDt = dt.AddDays(1 - Convert.ToDouble(dt.DayOfWeek))


wkEndDt = dt.AddDays(7 - Convert.ToDouble(dt.DayOfWeek))


Response.Write(wkStDt.ToString("MMMM-dd") & "<br/>")


Response.Write(wkEndDt.ToString("MMMM-dd"))


Creating a Dynamic Hyperlink in ASP.NET using the Web.Config

A user recently asked me that she wanted to create a bunch of hyperlinks whose value comes from a web.config. However she was not able to create the Hyperlink successfully by reading the key pair values. Here's how to do so:


  <appSettings>


    <add key="someurl" value="http://www.dotnetcurry.com" />


  </appSettings>




Now read this entry from the web.config using AppSettings


    <asp:HyperLink ID="HyperLink1" runat="server"


    NavigateUrl="<%$ Appsettings:someurl %>"  Text="Click Here">


    </asp:HyperLink>


Change DateFormat In an ASP.NET GridView

While displaying dates in the GridView, a very common requirement is to display the date format in a user friendly manner. By default, the HTMLEncode property of a BoundField is set to True, which makes it difficult to format the date.

Note: HTMLEncode=True helps prevent cross-site scripting attacks.

In order to display the date in a user friendly date format, use the following method to turn off the HTMLEncode and use :


<asp:GridView ID="GridView2" runat="server" AutoGenerateColumns="False" DataKeyNames="CustomerID"


DataSourceID="SqlDataSource1" AllowPaging="True" AllowSorting="True">


<Columns>


<asp:BoundField DataField="SomeDate" DataFormatString="{0:MM-dd-yyyy}"


HtmlEncode="false" HeaderText="SomeDate" />


...


</Columns>


</asp:GridView>




If you do not want to do it this way, the other way is to use a Template Field as shown below


<asp:GridView ID="GridView2" runat="server" AutoGenerateColumns="False" DataKeyNames="CustomerID"


DataSourceID="SqlDataSource1" AllowPaging="True" AllowSorting="True">


<Columns>


<asp:TemplateField HeaderText="SomeDate" >


<EditItemTemplate>


<asp:Label ID="lblDate" runat="server" Text='<%# Eval("SomeDate", "{0:MM-dd-yyyy}") %>'


</asp:Label>


</EditItemTemplate>




...


</Columns>


</asp:GridView>


Creating Sign-Up Forms? Get some ideas here!

I have always seen developers struggle while creating Sign-Up forms, especially the design part of it. It's always a challenge to pick the right CSS, use the right effect or for that matter name the fields. Here are some examples of some cool Sign-Up forms which I found very useful

Form field hints with CSS and JavaScript

CSS-Based Forms: Modern Solutions

Second Reminder - Become an MVP

If you have been actively contributing to the offline or online technical communities over the past year, here's your chance to get recognized and nominate yourself for the MVP Award

Nominate yourself today for this quarter's MVP Award. Last date 18th April 2009.

http://go.microsoft.com/?linkid=9658845

Return the First Element of a Sequence in LINQ

If you have a List<string> and want to quickly retrieve the first item of the sequence, use FirstOrDefault()

Enumerable.FirstOrDefault() returns the first element of a sequence, or a default value if the sequence contains no elements. For eg: Running the following query returns 'Jack'

C#


void Main()


{


    List<string> list = new List<string>() { "Jack", "And", "Jill", "Went", "Up", "The", "Hill" };


    var first = list.FirstOrDefault();


    Console.WriteLine(first);


}




VB.NET


Private Sub Main()


    Dim list As New List(Of String)(New String() {"Jack", "And", "Jill", "Went", "Up", "The", "Hill"})


    Dim first = list.FirstOrDefault()


    Console.WriteLine(first)


End Sub




Similarly if FirstOrDefault is used on an empty list of integers, it returns 0

How do you programmatically determine if an ASP.NET application is running locally

A user recently popped up a question on the forums asking if it was possible to determine that his asp.net app is running on the local machine. Well there were suggestions to check for the local address 127.0.0.1 or check http://localhost.

How to do this the reliable way, a very simple solution is to use the 'isLocal' property of the Request class as shown below:

C#


protected void Page_Load(object sender, EventArgs e)


{


    if (HttpContext.Current.Request.IsLocal)


    {


        Response.Write("App is local");


    }


}




VB.NET


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


        If HttpContext.Current.Request.IsLocal Then


            Response.Write("App is local")


        End If


    End Sub


Check your system for issues before installing Windows 7 or IE8

The Microsoft Application Compatibility Toolkit - ACT 5.5 contains the functionality to evaluate and mitigate compatibility issues before you go ahead and deploy Windows 7, Windows Vista, any Windows Update, or for that matter IE8.

You can also use the same tool to do a compatibility test of your website against the new IE8 browser or with a security update of IE8.

You can check out the ACT 5 Step by Step Guides and Download ACT 5.5 over here

Display an Image for EmptyData in an ASP.NET GridView

The GridView’s EmptyDataText property allows you display a message when there are no results returned from the GridView control’s data source.

However if you want to display an image instead of text when no results are returned, then here's how to do so:


<EmptyDataTemplate>


  <asp:Image id="imgNoData"


    ImageUrl="~/images/NoDataFound.jpg"


    AlternateText="No data found"


    runat="server"/>


 


</EmptyDataTemplate>




Shown above is an EmptyDataTemplate that can be used within the GridView. Inside the , we are using the image control to display an image when no records are returned

Submit a HTML Form using a Hyperlink

A user asked me recently on the forums if it was possible to Submit an HTML form without the Submit button. She wanted to do it using a Hyperlink instead.

Well it is possible to submit the form using a hyperlink with a small amount of JavaScript code as shown here:

<html xmlns="http://www.w3.org/1999/xhtml">
<
head>
<
title>Submit A HTML Form using a Hyperlink</title>

<
script type="text/javascript">
function
frmSubmit() {
document.form1.submit();
}
</script>
</
head>

<
body>
<
form name="form1" method="post" action="somescript.pl" >
<
div>
<
a href="javascript:frmSubmit();">Submit</a>
</
div>
</
form>
</
body>
That’s all you need!

Aligning two div's next to each other using CSS

I have been asked this question several times - How to align two DIV's next to each other using CSS. Here's a simple solution that I have been using for quite a while now:


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


<head runat="server">


    <title></title>


    <style type="text/css">


    div.Outer {


        width: 350px;


        border:dashed 1px black;


        position: relative;


        clear: both;


        }


 


        div.InnerLeft {


        width: 50%;


        position: relative;


        background: #CCCCCC;        


        float: left;


        }


 


        div.InnerRight {


        width: 49%;


        position: relative;


        background: #AAAAFF;        


        float: right;


        }


    </style>


</head>


<body>


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


    <div class="Outer">


        <div class="InnerLeft">


        Lorem Ipsum Lorem Ipsum Lorem Ipsum


        Lorem Ipsum Lorem Ipsum Lorem Ipsum


        Lorem Ipsum Lorem Ipsum Lorem Ipsum


        Lorem Ipsum Lorem Ipsum Lorem Ipsum


        Lorem Ipsum Lorem Ipsum Lorem Ipsum


        </div>


        <div class="InnerRight">


        Lorem Ipsum Lorem Ipsum Lorem Ipsum


        Lorem Ipsum Lorem Ipsum Lorem Ipsum


        Lorem Ipsum Lorem Ipsum Lorem Ipsum


        Lorem Ipsum Lorem Ipsum Lorem Ipsum


        Lorem Ipsum Lorem Ipsum Lorem Ipsum


        </div>


    </div>


    </form>


</body>


</html>




OUTPUT

ASP.NET MVC Training Kit

Microsoft has released the ASP.NET MVP Training Kit to help you get started with it.

The ASP.NET MVC Training Kit includes presentations, hands-on labs, demos, and event materials. I strongly recommend you to download and study this material.

ASP.NET MVC 1.0 can be downloaded from here. ASP.NET MVC is a new Model-View-Controller (MVC) framework on top of ASP.NET 3.5.

Adding OnClick event to an ASP.NET Label control

It's a strange requirement, but I bumped into it when helping out a user on the forums. Here's how to add an OnClick event to the ASP.NET Label Control


 


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


<head runat="server">


    <title></title>


    <script type="text/javascript">


        function CallMe() {


            alert('Hi');


        }


    </script>


</head>


<body>


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


    <div>


        <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>


    </div>


    </form>


</body>


</html>




Now in the Code Behind, use the Control.Attributes.Add() to add the OnClick event to the Label Control

C#


    protected void Page_Load(object sender, EventArgs e)


    {


        Label1.Attributes.Add("onClick", "CallMe();");


    }




VB.NET


 


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


    Label1.Attributes.Add("onClick", "CallMe();")


End Sub