Home » Visual Studio

How to add OnClientClick event for asp:MenuItem?


I'm stuck in a tricky situation and need help.  I'm using asp:menu control to display menu on my web page. I set navigation url property of each menu item to desired page and it works fine.

The problem is the menu items works only when one clicks at the text area but if some one clicks on the blank area after the text it does not work. I thought of OnClientClick event but it is not there for asp:MenuItem .

How can I achieve this so that no matter where one clicks on the menu item he is taken to the proper page.


2 Answers Found


Answer 1

The problem  is the menu  items works  only when one clicks  at the text  area but if some one clicks on the blank area  after the text it does not work. I thought  of OnClientClick event  but it is not there for asp:MenuItem .

How can I achieve  this so that no matter  where one clicks on the software menu item  he is taken to the proper  page.

I'm a new hand, but it seems to me the menu items  are just designed in that way. Maybe you have to try other ways to achieve that.

Answer 2


maybe you colud try their way:



you could add  click event  on client pageLoad(asp.net ajax or jquery)



This code example comes directly from MSDN at http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.menu.menuitemclick.aspx

My question is, say, I wanted to add some sort of confirmation prompt, like a javascript confirm() dialog for when the user selects the "Drama" option.

In other words, I before the page writes "you chose Drama" I want to challenge the user with "are you sure you want to choose drama?".

Can this be done?


<%@ Page Language="VB" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
<script runat="server">

  Sub NavigationMenu_MenuItemClick(ByVal sender As Object, ByVal e As MenuEventArgs)

    ' Display the text of the menu item selected by the user.
    Message.Text = "You selected " & _
      e.Item.Text & "."

  End Sub


<html  >
  <head id="Head1" runat="server">
    <title>Menu MenuItemClick Example</title>
    <form id="form1" runat="server">

      <h3>Menu MenuItemClick Example</h3>

      <asp:menu id="NavigationMenu"        staticdisplaylevels="2"        staticsubmenuindent="10"        orientation="Vertical"        onmenuitemclick="NavigationMenu_MenuItemClick"        runat="server">

          <asp:menuitem text="Home"            tooltip="Home">
            <asp:menuitem text="Music"              tooltip="Music">
              <asp:menuitem text="Classical"                tooltip="Classical"/>
              <asp:menuitem text="Rock"                tooltip="Rock"/>
              <asp:menuitem text="Jazz"                tooltip="Jazz"/>
            <asp:menuitem text="Movies"              tooltip="Movies">
              <asp:menuitem text="Action"                tooltip="Action"/>
              <asp:menuitem text="Drama"                tooltip="Drama"/>
              <asp:menuitem text="Musical"                tooltip="Musical"/>



      <asp:label id="Message"        runat="server"/>



i've a form.in that i'm using save button to save the values in the form into db.there are some required fields,email.i'm doing this validation using js.i've written the code for validations.it's displaying error message also.but it's not restricting the saving entered values into db.how to restrict this?can any one help me?


I'm having problems redirecting the user when they click a button. Below is an example.

This is what I'm trying to do in order to redirect, but I keep getting an error stating that the tag is not well formed: 

<asp:Button ID="Button4" runat="server" Text="Button" onclientclick="location.href='closed.aspx?storeID=<%#Eval("storeID")%>'"/>
This does work, just did it as a test:                                                
<asp:Button ID="Button2" runat="server" Text="Button" onclientclick="alert('hello');"/>
Why does my redirect not work? It works fine in a regular button, but not in the asp button. Am I missing something?
Thanks in advance. 

I have a page where I need to both run server side code on an ASP.NET button click, but also target a new window.  I'm using the OnClientClick='aspnetForm.target='_blank' trick to do this and it works fine.

However, we just released a new version of our application where we changed the <pages> node in the web.config to use the new Predictable ClientID setting as the default.  We also set controlRenderingCompatibilityVersion to 4.0.

This causes that trick to stop working.  For now I've used a location setting in the web.config for that specific directory with controlRenderingCompatibilityVersion set back to 3.5.  I also set the ClientID setting for the page in question back to AutoID.  Using these settings, it is working again, but I'm curious if there is a supported way to keep using this trick and use the latest settings.


I have a user control that contains another user control based on a button. When the button is clicked I have it show a context menu that is bound to a enumeration that shows a dynamic set of menu items. I use a HierarchicalDataTemplate to generate the MenuItems and use a style with an eventsetter to define a menu click handler to be called when any of the menu items are clicked. The context menu and its menu items gets displayed properly but the event handler is not getting called. Any ideas? Below is the section of the xaml where the user control is defined and below it is the code behind with the event handler.



<Controls:WebcastButton x:Uid="videoConfigureButton" x:Name="videoConfigureButton" 
                                                Grid.Row="0" Grid.Column="2"
                                                FontSize="9" CornerRadius="7"
                                                HorizontalAlignment="Center" VerticalAlignment="Center"
                                                Content="{lex:LocTextUpper DeviceSourceView_ConfigureButtonText}"
                                                ToolTip="Configure the video device" 

                                    <HierarchicalDataTemplate DataType="{x:Type MenuItem}">
                                            <Style TargetType="MenuItem">
                                                <EventSetter Event="MenuItem.Click" Handler="MenuItem_Click"/>

                                    <ContextMenu ItemsSource="{Binding VideoConfigurationDialogs}"/>

        private void videoConfigureButton_Click(object sender, RoutedEventArgs e)
            videoConfigureButton.ContextMenu.Placement = System.Windows.Controls.Primitives.PlacementMode.Bottom;
            videoConfigureButton.ContextMenu.PlacementTarget = videoConfigureButton;
            videoConfigureButton.ContextMenu.IsOpen = true;

        private void MenuItem_Click(object sender, RoutedEventArgs e)



I have created a event handler which executes the custom code at in item adding and item added event. 


But some times i have observed that, the both the events are not getting fired.


Any Help in this regards will be great.   


Thanks in advance.


    protected void myMenu_MenuItemClick(object sender, MenuEventArgs e)
     lbl.Text = "This will not appear on the page";

why this event doesn't trigger. the page  loads normally but nothing happens in this case the label is not updated.


I'm writing a library and project that uses the library in the same time. The library contains form that has menuStrip in it. In my project I need to create main window that inherit this form. Is it possible to access the menuStrip (protected) and add via designer new menuItems in main window? Thank you for any help.

Hello, and thank you for taking a look at this question.

I am developing my own Most Recent Used sub-menu. I have developed my main File Menu items (Open, Close, Save etc) in my XAML and included a binding for these to my commands which are defined in my ViewModel. These all work fine.

I have decided to save the file path and date into an XML file for simplicity. I can read this in and in my ViewModel I have a ListCollectionView property which exposes the XML elements. Still fine!

In my XAML I can bind my Recent Items sub-menu to the Filename item in my ListCollectionView without a problem, but I cannot seem to figure out how to bind each sub-menu item to a Command which will determine which file to open.

My XAML so far is as follows:

            x:Name="MainMenu" Background="#FFFFFFFF" BorderBrush="#FF000000" Margin="0,0,0,2.723" Grid.ColumnSpan="2" d:LayoutOverrides="Height, GridBox">
            <MenuItem Header="_File">
                <MenuItem Header="_Open" InputGestureText="Ctrl+O" Command="{Binding Path=OpenCommand}"/>
                <MenuItem Header="_New" InputGestureText="Ctrl+N" Command="{Binding Path=NewCommand}"/>
                <MenuItem Header="_Close" InputGestureText="Ctrl+Q" Command="{Binding Path=CloseCommand}"/>
                <MenuItem Header="_Save" InputGestureText="Ctrl+S"/>

                <MenuItem Header="Open _Recent" ItemsSource="{Binding Path=RecentFiles}">
                        <Style TargetType="{x:Type MenuItem}">
                            <Setter Property="Header" Value="{Binding Filename}"/>
                            <Setter Property="ItemsSource" Value="{Binding RecenFiles}"/>
                            <Setter Property="Command" Value="{Binding Path=OpenRecentCommand}" />
            <MenuItem Header="_Help">
                <MenuItem Header="_About" InputGestureText="Ctrl+A"/>
I think at the moment my XAML is trying to bind the Command to an item in my RecentFiles ListCollectionView.

I would be very grateful for some guidance as to how I can open the file, once selected, using my OpenRecentCommand method in my ViewModel.

Thank you.

Howdo I addanitem?

my Code:

                       <toolkit:MenuItem Header="Desktop" Name="Mnu_DeskTop" >
                                <toolkit:MenuItem Header="Desk 2"></toolkit:MenuItem>

Error Message:

The method or operation is not implemented

Will COM Add-in event handlers conflict with Word macro event handlers? I have a Word 2003 template with the Document_New() and Document_Open() event handlers. I open this template with Word 2007. When the Adobe PDFMaker COM Add-in or the SearchCommand Add-in is enabled, the Document_New() or Open() events never fire. It appears that they are wiped out by the COM Add-in or the add-ins prevents the template from loading correctly. I say this, because looking in the VBA code only shows the macros from the COM Add-Ins. The COM Add-in macros are event handlers including Initialize() and several different CompileNow() event handlers.

If they do conflict, is there a way to cause the Word macro event handler to be in effect and exclude the add-in event handler?

Thanks in advance for any help,


Enjoy your day, Joe

Hello everybody.

Could you help me. I have textbox, RequiredFieldValidator for it and Button with OnClientClick property.



<asp:ButtonID="Button1"runat="server"Text="Button"OnClientClick="return confirm('are you sure?')"OnClick="Button1_Click"/>

When I click Button and then OK in dialog box, RequiredFieldValidator doesn't validate the TextBox on client-side, only on server-side. How can I avoid overloading of page?




I work in VS 2008. Whenver I add a server control(Label) and set it properties in aspx.vb and build the solution, I get the error "Label1 not declared". While analyzing this issue I noticed that the event handler statements for the Label1 where not added in the designer.asp.vb file. These statement would actually be added automatically when I drag and drop a control to my webpage.

I would also like to inform the scenario after which this problem came to me. I was working in VS 2008 , VS 2005 and VS 2003 in the same machine.Could this have caused the issue ? Please advise.

Now each and everytime when I add a control, I am adding the "With Events" code in the designer page to make my build succesfull which makes me to spend more efforts.

Please advise if any settings have to be changed.





I have a GridView with a couple of buttons (asp:Button) in it (last row). Both of them have a CommandName attribute on them and this is handled server side in a grid_RowCommand event handler. Now, this works fine. However, I need to add client side code (Javascript/jQuery) to disable the two buttons when someone clicks on or the other. This is to prevent the user from double-clicking and creating potential havoc. 
The way I have done this is by adding OnClientClick on both buttons which calls a javascript function that uses jQuery to disable the two buttons. This works fine, it's just that the page doesn't post back and so the RowCommand event handler never fires.

Here's the essential code:

function DisableButtons() {
$("[id$='btnNewEntry']").attr("disabled", true);
$("[id$='btnSave']").attr("disabled", true);


<asp:Button ID="btnNewEntry" runat="server" Text="New Entry" OnClientClick="DisableButtons();" CommandName="Add" />&nbsp;&nbsp;
<asp:Button ID="btnSave" runat="server" Text="Save" OnClientClick="DisableButtons();" CommandName="Save" />

I have tried doing a return true in the javascript function and in OnClientClick without luck. 

Can anyone please help me out?


function DisableButtons()
$("[id$='btnNewEntry']").attr("disabled", true);
$("[id$='btnSave']").attr("disabled", true);



I have a datalist which I have put  an imagebutton in. I want the button to trigger some javascript to play an MP3, but I need to dynamically add the onClientClick..

I am doing this  onItemDatabound , I thought it would be quite simple...

dim ImagePlay as imagebutton = e.item.findcontrol("image_PLAY")

imagePlay.onClientClick = "wimpyButtonPlayPause('" & varMP3link & "')"

That adds the correct 'onclick' event in - but the javascript doesn't fire. When I look at the source code on the browser, the single quotes have been replaced with a hex code. Why would that be and can I stop it?




I am looking to add an ASP.NET button to add a page viewer web part to a SharePoint page.  I have SP 2010 and I have been using SPD 2010.  I am able to add the button but I am new and I'm not sure how to add the onclick code to add the web part to the SP page.

I have written a custom menu for SharePoint. I get my data from PublishingNavigation:PortalSiteMapDataSource.


But when I try and get the .Target from the MenuItem, it is always empty. Even if I have the menu set to "display in new window". The regular sharepoint menu works, so I know the data is good.

Here is my code.

public class LeftNavigationMenu : Menu  
        #region Render  
        protected override void Render(HtmlTextWriter writer)  
            MenuItemCollection items = this.Items;  
            string leftnavigation = CreateLeftNavigation(items);  
        #region CreateLeftNavigation  
        public string CreateLeftNavigation(MenuItemCollection items)  
            string navigationlist = string.Empty;  
            string listitem = string.Empty;  
            StringBuilder sbNavigationString = new StringBuilder();  
            //add the style for this list grouping  
            //add the list tag  
            sbNavigationString.AppendLine(" <ul class=\"left-menu\">");  
            // set a counter  
            int i = 0;  
            //write out the list items  
            foreach (MenuItem item in items)  
                //start the list item, set the class and get the item  
HERE->>>>>>>    listitem = string.Format("<li><ahref=\"{0}\" target={1}>{2}</a></li>", item.NavigateUrl, item.Target, item.Text);
                //add the item to the stringbuilder  
            sbNavigationString.AppendLine(" </ul> ");  
navigationlist = sbNavigationString.ToString();  
            return navigationlist;  

Hello Experts!

I have generated a Table dynamically with Button

Now, I am inserting a row on this Button Click event through a Button Click Event Handler.

Once I click the button one row is inserted, but then when I refresh the page,

It again goes to Button Event Handler method and insert the same row again, even if I don't clicked the Button.

Kindly guide me.


I'm working on a bug with an existing application that I did not originally create.  The client is a Win Forms app, and it communicates with an ASP.NET Web Application with an ASP.NET Service.  I'm currently converting some synchronous calls that lock up the GUI thread for too long into asynchronous calls.  The proxy class for the ASP.NET service already had the async methods.  Under normal circumstances, everything works as expected, but if an exception is thrown in the service method on the server, the exception bubbles up to my client app's AppDomain.CurrentDomain.UnhandledException handler, instead of returning execution immediately to the completed event I hooked up (which is what I was expecting).  Does anyone know why or what would cause the completed event handler not to be fired when an exception occurs on the server?  Could a web.config setting be missing from the service or something?  I tried creating a simple example, but it worked fine, so I definitely know there's something fishy going on.  I even commented out the entire web.config in my sample project, and it still worked, so I figure it has nothing to do with that.  Any ideas?


Can anyone help please?  I've just gone live with a new website, and am now getting some application warnings, and users complaining that they've lost their session.

An example of one of the errors is:

Event code: 3005

Event message: An unhandled exception has occurred.

Event time: 17/08/2010 15:16:55

Event time (UTC): 17/08/2010 14:16:55

Event ID: 633aed09616e43e7bce02cc1a8193f40

Event sequence: 140

Event occurrence: 3

Event detail code: 0


Application information:

Application domain: /LM/W3SVC/2067614354/Root-1-129265267981495795

Trust level: Full

Application Virtual Path: /

Application Path: D:\InetPub\MyWeb\

Machine name: MyServer


Process information:

Process ID: 3860

Process name: w3wp.exe



Exception information:

Exception type: HttpUnhandledException

Exception message: Exception of type 'System.Web.HttpUnhandledException' was thrown.


Request information:

Request URL: http://abc.co.uk/Registration System/FindPerson/Default.aspx

Request path: /Registration System/FindPerson/Default.aspx

User host address:


Is authenticated: False

Authentication Type:



Thread information:

Thread ID: 8


Is impersonating: False

Stack trace: at System.Web.UI.Page.HandleError(Exception e)

at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)

at System.Web.UI.Page.ProcessRequest(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)

at System.Web.UI.Page.ProcessRequest()

at System.Web.UI.Page.ProcessRequestWithNoAssert(HttpContext context)

at System.Web.UI.Page.ProcessRequest(HttpContext context)

at ASP.registration_system_findperson_persondetails_aspx.ProcessRequest(HttpContext context) in c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files\root\4cbe237f\50a7a1bb\App_Web_ekky3ewa.4.cs:line 0

at System.Web.HttpServerUtility.ExecuteInternal(IHttpHandler handler, TextWriter writer, Boolean preserveForm, Boolean setPreviousPage, VirtualPath path, VirtualPath filePath, String physPath, Exception error, String queryStringOverride)



Custom event details:

For more information, see Help and Support Center at http://go.microsoft.com/fwlink/events.asp.


Many thanks




<< Previous      Next >>

Microsoft   |   Windows   |   Visual Studio   |   Sharepoint   |   Azure