Change in PopulateMenu Method like below.
C#
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);
if (parentMenuId > 0)
{
DataTable dtChild = this.GetData(int.Parse(menuItem.Value));
PopulateMenu(dtChild, int.Parse(menuItem.Value), menuItem);
}
}
}
}
VB.Net
Private Sub PopulateMenu(dt As DataTable, parentMenuId As Integer, parentMenuItem As MenuItem)
Dim currentPage As String = Path.GetFileName(Request.Url.AbsolutePath)
For Each row As DataRow In dt.Rows
Dim menuItem As New MenuItem() With { _
.Value = row("MenuId").ToString(), _
.Text = row("Title").ToString(), _
.NavigateUrl = row("Url").ToString(), _
.Selected = row("Url").ToString().EndsWith(currentPage, StringComparison.CurrentCultureIgnoreCase) _
}
If parentMenuId = 0 Then
Menu1.Items.Add(menuItem)
Dim dtChild As DataTable = Me.GetData(Integer.Parse(menuItem.Value))
PopulateMenu(dtChild, Integer.Parse(menuItem.Value), menuItem)
Else
parentMenuItem.ChildItems.Add(menuItem)
If parentMenuId > 0 Then
Dim dtChild As DataTable = Me.GetData(Integer.Parse(menuItem.Value))
PopulateMenu(dtChild, Integer.Parse(menuItem.Value), menuItem)
End If
End If
Next
End Sub