Friday, July 9, 2010

Asp.Net Menu. deleting an Item in Runtime

Sometimes we need to delete (hide) a menu item from an aspnet web application menu (or submenu) when a particolar condition occurs. The problem is that the menu component doesn't have a method to hide a menuitem during runtime. Well, here you have the code to do it:

Protected Sub Menu1_PreRender(ByVal sender As Object, ByVal e As System.EventArgs) Handles Menu1.PreRender
        'delete the unnecessary menu item
        Dim tot As Integer = Menu1.Items.Count - 1
        Dim i As Integer = 0
            While i <= tot
            Dim ss As MenuItem = Menu1.Items(i)
            If ss.Text.ToLower = "menu name" Then
                'delete sub menus
                Dim subtot As Integer = Menu1.Items(i).ChildItems.Count - 1
                Dim j As Integer = 0
                While j <= subtot
                    j += 1
                End While
                'delete menu
                i = i - 1
                tot = tot - 1
            End If
            i += 1
        End While
    End If
End Sub