how to add menuItemClick event when menuItem is created programatically in asp.net?

Saravanan picture Saravanan · Jan 17, 2013 · Viewed 12.5k times · Source

In my asp.net web application, i have created a menu and menuItem programatically based on the Logged in user role.The Code is given below...

    Menu menu = new Menu();
    menu.CssClass = "menu";
    menu.IncludeStyleBlock = false;
    menu.EnableViewState = false;
    menu.Orientation = Orientation.Horizontal;

    if (roleType.equals("teacher"))
    {
        MenuItem categoryItemCh1 = new MenuItem("Home");
        categoryItemCh1.NavigateUrl = "Teacher/TestsList.aspx";
        menu.Items.Add(categoryItemCh1);

        MenuItem categoryItemCh2 = new MenuItem("Account");
        categoryItemCh2.NavigateUrl = "Account/underconstruction.aspx";
        menu.Items.Add(categoryItemCh2);

        MenuItem categoryItemCh3 = new MenuItem("Reports");
        categoryItemCh3.NavigateUrl = "Account/underconstruction.aspx";
        menu.Items.Add(categoryItemCh3);

        MenuItem categoryItemCh4 = new MenuItem("Logout");
        menu.Items.Add(categoryItemCh4);
    }

So, When user clicks the logout menu item , then i have to fire menuItem click event to do the following process.

1.Clear all the session associated with the user
2.Redirect to Login page.

But i don't know how to add a menuItem click event programatically in asp.net.Please guide me to get out of this issue...

Answer

keifer94 picture keifer94 · Jan 17, 2013

Use the MenuItemClick event. You don't add an event to each menu item but to the menu itself

menu.OnMenuItemClick += Menu_MenuItemClick;


void Menu_MenuItemClick(Object sender, MenuEventArgs e)
{
// Display the text of the menu item selected by the user.
Message.Text = "You selected " + 
  e.Item.Text + ".";
}

You can use the MenuEventArgs to figure out which menu item was clicked