Sunday, December 2, 2012

Asp.net menu from Web.sitemap with separators

If you use the Web.sitemap file to automatically generate Asp.net menu items, you immediatly notice all the items are "grouped together" and is not possible to put a separator. But if you use the code below, it's possible.

In the Web.sitemap file (for each node you want have a separator before):



Into code:

Protected Sub Menu1_MenuItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.MenuEventArgs) Handles Menu1.MenuItemDataBound
    If e.Item.Text.IndexOf("[sep]") > 0 Then
        e.Item.Text = e.Item.Text.Replace("[sep]", "")
        e.Item.SeparatorImageUrl = Page.ResolveUrl("~/Common/images/dividerhoriz.gif")
    End If
 
    Try
        If Menu1.SelectedItem Is Nothing Then
            If IsNodeAncestor(CType(e.Item.DataItem, SiteMapNode), System.Web.SiteMap.CurrentNode) Then
                If e.Item.Selectable Then
                    e.Item.Selected = True
                End If
            End If
        End If
    Catch ex As Exception
 'Exception management
    End Try
End Sub
 
''' 
''' Determines if a  is the ancestor of a second one.
''' 
''' The  to analyze.
''' A  which may or may not be 
''' the 's child.
''' true, if the two nodes are related, false otherwise.
Private Function IsNodeAncestor(ByVal ancestor As SiteMapNode, ByVal child As SiteMapNode) As Boolean
    Dim result As Boolean = False
    Try
        If Not ancestor.ChildNodes Is Nothing AndAlso ancestor.ChildNodes.Contains(child) Then
            Return True
        Else
            If (Not child.ParentNode Is Nothing) AndAlso (Not ancestor Is child.RootNode) Then
                Return IsNodeAncestor(ancestor, child.ParentNode)
            End If
        End If
    Catch ex As Exception
 'Exception management
        Return False
    End Try

    Return result
End Function
 
Protected Sub SiteMapPath1_ItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.SiteMapNodeItemEventArgs) Handles SiteMapPath1.ItemDataBound
    If Not e.Item.SiteMapNode Is Nothing Then
        If e.Item.SiteMapNode.Title.IndexOf("[sep]") >= 0 Then
            Try
                e.Item.SiteMapNode.Title = e.Item.SiteMapNode.Title.Replace("[sep]", "")
            Catch
  'Exception management
            End Try
        End If
    End If
End Sub

No comments: