Hi atul1948,
To check which menu item is clicked you need to write code in OnMenuItemClick event.
As we are bind the NavigateUrl of the Menu item, it will not raise the MenuItemClick event, becuase it directly redirect to another new page.
To raise the MenuItemclick event do not bind the NavigateUrl property of Menu item.
Then you will get the selected menu item.
HTML
<asp:Menu ID="Menu1" runat="server" Orientation="Horizontal" OnMenuItemClick="Menu1_MenuItemClick">
<LevelMenuItemStyles>
<asp:MenuItemStyle CssClass="main_menu" />
<asp:MenuItemStyle CssClass="level_menu" />
</LevelMenuItemStyles>
<StaticSelectedStyle CssClass="selected" />
</asp:Menu>
<hr />
<asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server">
</asp:ContentPlaceHolder>
C#
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
DataTable dt = this.GetData(0);
PopulateMenu(dt, 0, null);
}
}
private DataTable GetData(int parentMenuId)
{
string query = "SELECT [MenuId], [Title], [Description], [Url] FROM [Menus] WHERE ParentMenuId = @ParentMenuId";
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
DataTable dt = new DataTable();
using (SqlCommand cmd = new SqlCommand(query))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Parameters.AddWithValue("@ParentMenuId", parentMenuId);
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
sda.SelectCommand = cmd;
sda.Fill(dt);
}
}
return dt;
}
}
private void PopulateMenu(DataTable dt, int parentMenuId, MenuItem parentMenuItem)
{
string currentPage = Path.GetFileName(Request.Url.AbsolutePath);
foreach (DataRow row in dt.Rows)
{
MenuItem menuItem = new MenuItem
{
Value = row["MenuId"].ToString(),
Text = row["Title"].ToString(),
//NavigateUrl = row["Url"].ToString(),
Selected = row["Url"].ToString().EndsWith(currentPage, StringComparison.CurrentCultureIgnoreCase)
};
if (parentMenuId == 0)
{
Menu1.Items.Add(menuItem);
DataTable dtChild = this.GetData(int.Parse(menuItem.Value));
PopulateMenu(dtChild, int.Parse(menuItem.Value), menuItem);
}
else
{
parentMenuItem.ChildItems.Add(menuItem);
}
}
}
protected void Menu1_MenuItemClick(object sender, MenuEventArgs e)
{
string selectedItem = (sender as Menu).SelectedItem.Text;
ScriptManager.RegisterStartupScript(this, this.GetType(), "", "alert('Selected Menu is : " + selectedItem + "')", true);
}
Screenshot