Follow the steps below:
Getting the Menu Data From database:
private DataTable GetMenuData()
{
try
{
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["MenuWithCustomPrivs"].ConnectionString))
{
SqlCommand cmd = new SqlCommand("spMenuItem", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@UserID", "K010");
DataTable dtMenuItems = new DataTable();
SqlDataAdapter sda = new SqlDataAdapter(cmd);
sda.Fill(dtMenuItems);
cmd.Dispose();
sda.Dispose();
return dtMenuItems;
}
}
catch (Exception ex) {
}
return null;
}
Adding the top/parent menu items:
private void AddTopMenuItems(DataTable menuData)
{
DataView view = null;
try
{
view = new DataView(menuData);
view.RowFilter = "ParentID IS NULL";
foreach (DataRowView row in view)
{
MenuItem newMenuItem = new MenuItem(row["Text"].ToString(), row["MenuID"].ToString());
menuBar.Items.Add(newMenuItem);
AddChildMenuItems(menuData, newMenuItem);
}
}
catch (Exception ex)
{
}
finally {
view = null;
}
}
Adding child menu items:
private void AddChildMenuItems(DataTable menuData, MenuItem parentMenuItem)
{
DataView view = null;
try
{
view = new DataView(menuData);
view.RowFilter = "ParentID=" + parentMenuItem.Value;
foreach (DataRowView row in view)
{
MenuItem newMenuItem = new MenuItem(row["Text"].ToString(), row["MenuID"].ToString());
newMenuItem.NavigateUrl = row["NavigateUrl"].ToString();
parentMenuItem.ChildItems.Add(newMenuItem);
AddChildMenuItems(menuData, newMenuItem);
}
}
catch (Exception ex)
{
}
finally
{
view = null;
}
}
Hope it helps.!
--Amit