Hi everybody,
I am a new guy.
This is the first time I have posted a question.
I hope get some answers and advices.
I want to make a menu user control which can display n-level sub-categories from database.
Firstly, I have already retrieved the data with recursion method.
Next, I want to display the data with menu just like the Codeproject's, and I have a problem with that.
If anybody can help me to solve this problem which bothers me some times, I'll appreciate.
This is my data table:
id menu_name parent_id
1 home 0
2 news 0
3 about 0
4 introduction 1
5 localnews 2
6 globalnews 2
7 contact 3
This is my code:
using System;
using System.Web;
using System.Web.UI.WebControls;
using System.Data.OleDb;
using System.Data;
public partial class About : System.Web.UI.Page
{
public static string connstring = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + System.Web.HttpContext.Current.Server.MapPath("~/App_Data/menu.mdb");
OleDbConnection conn = new OleDbConnection(connstring);
protected void Page_Load(object sender, EventArgs e)
{
this.menu.Text = queryAllMenu(0, conn);
}
public string queryAllMenu(int id, OleDbConnection conn)
{
string Result = id.ToString();
string cmd_Sql = "SELECT * FROM menu_table WHERE parent_id =" + id;
try
{
DataSet ds = new DataSet();
OleDbDataAdapter cmd = new OleDbDataAdapter(cmd_Sql, conn);
cmd.Fill(ds, "menu");
DataTable dt = ds.Tables["menu"];
for (int i = 0; i < dt.Rows.Count; i++)
{
int menu_num = Convert.ToInt32(dt.Rows[i][0].ToString());
if ("".Equals(Result))
Result += menu_num;
else
Result += ", " +dt.Rows[i]["menu_name"] + "<br />";
string sub_menu = menuChild(menu_num, conn);
if (!"".Equals(sub_menu))
Result += sub_menu+ "<br />";
}
if (conn.State != ConnectionState.Closed)
conn.Close();
}
catch
{
return Result;
}
return Result;
}
private string menuChild(int Parent_Id, OleDbConnection conn)
{
string Result = string.Empty;
string cmdSql = "SELECT * FROM menu_table WHERE parent_id =" + Parent_Id;
try
{
DataSet ds = new DataSet();
OleDbDataAdapter cmd = new OleDbDataAdapter(cmdSql, conn);
cmd.Fill(ds, "dropdown_menu");
DataTable dt = ds.Tables["dropdown_menu"];
for (int i = 0; i < dt.Rows.Count; i++)
{
int id = Convert.ToInt32(dt.Rows[i][0].ToString());
if ("".Equals(Result))
Result += dt.Rows[i]["menu_name"];
else
Result += "," + dt.Rows[i]["menu_name"];
Result += menuChild(id, conn);
}
if (conn.State != ConnectionState.Closed)
conn.Close();
}
catch
{
return Result;
}
return Result;
}
}
[edit]Inline codes converted to Code blocks - OriginalGriff[/edit]