I am creating a data-driven dynamic menu in asp.net, using sql server 2008 R2 as my database. The parent node, and child nodes at the first level works just fine. but the child node below another child node, the application generate an exception. The c# code for my problem is as follows :
public partial class LeaveManagementSystemMasterPage : System.Web.UI.MasterPage
{
SqlConnection conn;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
getMenu();
}
}
private void getMenu()
{
Connect();
conn.Open();
DataSet ds = new DataSet();
DataTable dt = new DataTable();
string sqlQuery = "select * from menu";
SqlDataAdapter da = new SqlDataAdapter(sqlQuery, conn);
da.Fill(ds);
dt = ds.Tables[0];
DataRow[] rowParent = dt.Select("ParentID=" + 0);
DataRow[] rowChild = dt.Select("ParentID>"+0);
//populating the first level of the menu
foreach (DataRow dr in rowParent)
{
Menu1.Items.Add(new MenuItem(dr["MenuName"].ToString(),dr["MenuID"].ToString(),"",""));
}
//populating the children in menu
foreach (DataRow dr in rowChild)
{
MenuItem child = new MenuItem(dr["MenuName"].ToString(), dr["MenuID"].ToString(), "", "");
Menu1.FindItem(dr["ParentID"].ToString()).ChildItems.Add(child);
}
conn.Close();
}
public void Connect()
{
string conStr="Data Source=HO-0000-LAP; Initial Catalog=LeaveManagementSystem; Integrated Security=true";
conn = new SqlConnection(conStr);
}
}
And here is my table which i have designed in sqlserver 2008 :-