Generate Dynamic Menu in ASP.NET
Sometimes we need to generate menu form database
according to our requirements. The following code will help you to generate
menu dynamically in ASP.NET. You can apply your customize CSS as you like to
give nice outlook of the menu.
Table Creation
At first run the following SQL scripts in your
database. This will create Menus table with some sample data.
CREATE TABLE [dbo].[Menus](
[MenuID] [bigint] NOT NULL,
[ParentID] [bigint] NULL,
[Name] [nvarchar](50) NULL,
[URL] [nvarchar](50) NULL,
CONSTRAINT
[PK_Menus] PRIMARY KEY
CLUSTERED
(
[MenuID] ASC
)WITH
(PAD_INDEX
= OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS
= ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
INSERT [dbo].[Menus] ([MenuID], [ParentID], [Name], [URL]) VALUES (1, 0, N'Main Menu1', N'Main Menu1')
INSERT [dbo].[Menus] ([MenuID], [ParentID], [Name], [URL]) VALUES (2, 0, N'Main Menu2', N'Main Menu2')
INSERT [dbo].[Menus] ([MenuID], [ParentID], [Name], [URL]) VALUES (3, 0, N'Main Menu3', N'Main Menu3')
INSERT [dbo].[Menus] ([MenuID], [ParentID], [Name], [URL]) VALUES (4, 1, N'Sub Menu 1.1', N'Sub Menu 1.1')
INSERT [dbo].[Menus] ([MenuID], [ParentID], [Name], [URL]) VALUES (5, 1, N'Sub Menu 1.2', N'Sub Menu 1.2')
INSERT [dbo].[Menus] ([MenuID], [ParentID], [Name], [URL]) VALUES (6, 2, N'Sub Menu 2.1', N'Sub Menu 2.1')
INSERT [dbo].[Menus] ([MenuID], [ParentID], [Name], [URL]) VALUES (7, 2, N'Sub Menu 2.2', N'Sub Menu 2.2')
INSERT [dbo].[Menus] ([MenuID], [ParentID], [Name], [URL]) VALUES (8, 3, N'Sub Menu 3.1', N'Sub Menu 3.1')
INSERT [dbo].[Menus] ([MenuID], [ParentID], [Name], [URL]) VALUES (9, 3, N'Sub Menu 3.2', N'Sub Menu 3.2')
INSERT [dbo].[Menus] ([MenuID], [ParentID], [Name], [URL]) VALUES (10, 3, N'Sub Menu 3.2', N'Sub Menu 3.3')
Connection String
Write connection string in web.config file according
to your database credential. A sample connection string code is:
<connectionStrings>
<add name="ConStr" connectionString="Data Source=.;Initial Catalog=TestDB;Persist Security
Info=True;User ID=sa;Password=sa"
providerName="System.Data.SqlClient"/>
</connectionStrings>
C# Code
Paste the following C# code in your master page of ASP.NET
project.
protected void Page_Load(object sender, EventArgs
e)
{
if (!IsPostBack)
{
DataTable oDataTable = new
DataTable();
oDataTable = SelectDataTable("SELECT MenuID, ParentID, Name, URL FROM Menus");
DataRow[] drParentMenu = oDataTable.Select("ParentID = 0");
var oStringBuilder = new
StringBuilder();
string MenuList = GenerateMenu(drParentMenu,
oDataTable, oStringBuilder);
Literal1.Text = MenuList;
}
}
private
string GenerateMenu(DataRow[]
drParentMenu, DataTable oDataTable, StringBuilder oStringBuilder)
{
oStringBuilder.AppendLine("<ul>");
if
(drParentMenu.Length > 0)
{
foreach
(DataRow dr in
drParentMenu)
{
string
MenuURL = dr["URL"].ToString();
string
MenuName = dr["Name"].ToString();
string
line = String.Format(@"<li ><a
href=""{0}"">{1}</a>", MenuURL,
MenuName);
oStringBuilder.Append(line);
string
MenuID = dr["MenuID"].ToString();
string
ParentID = dr["ParentID"].ToString();
DataRow[]
subMenu = oDataTable.Select(String.Format("ParentID = {0}", MenuID));
if
(subMenu.Length > 0 && !MenuID.Equals(ParentID))
{
var
subMenuBuilder = new StringBuilder();
oStringBuilder.Append(GenerateMenu(subMenu,
oDataTable, subMenuBuilder));
}
oStringBuilder.Append("</li>");
}
}
oStringBuilder.Append("</ul>");
return
oStringBuilder.ToString();
}
public string GetConnectionStrings()
{
string
ConStr = ConfigurationManager.ConnectionStrings["ConStr"].ConnectionString;
return
ConStr;
}
public DataTable
SelectDataTable(String Sql)
{
DataTable
dt = new DataTable();
SqlConnection
oSqlConnection = new SqlConnection(GetConnectionStrings());
try
{
oSqlConnection.Open();
SqlDataAdapter
sqlda = new SqlDataAdapter(Sql,
GetConnectionStrings());
sqlda.Fill(dt);
}
catch (Exception ex)
{
throw
new Exception(ex.Message);
}
finally
{
oSqlConnection.Close();
oSqlConnection.Dispose();
}
return
dt;
}
Output
If you run your project you will find the following output
0 comments:
Post a Comment