データベースからメニューを作成し、メニュー コントロールに表示したいと考えています。
.aspx ページのコード:
<asp:Menu ID="Menu1" Orientation="horizontal" StaticMenuItemStyle-CssClass="menuItem"
DynamicMenuItemStyle-CssClass="menuItem" runat="server">
マスターの .cs ページ:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
populateMenuItem();
}
}
private void populateMenuItem()
{
DataTable menuData = GetMenuData();
AddTopMenuItems(menuData);
}
/// Filter the data to get only the rows that have a
/// null ParentID (This will come on the top-level menu items)
private void AddTopMenuItems(DataTable menuData)
{
DataView view = new DataView(menuData);
view.RowFilter = "DepartmentParentID IS NULL";
foreach (DataRowView row in view)
{
//MenuItem newMenuItem = new MenuItem(row["DepartmentName"].ToString(), row["DepartmentID"].ToString());
MenuItem newMenuItem = new MenuItem(row["DepartmentName"].ToString(), row["DepartmentID"].ToString());
Menu1.Items.Add(newMenuItem);
AddChildMenuItems(menuData, newMenuItem);
}
}
//This code is used to recursively add child menu items by filtering by ParentID
private void AddChildMenuItems(DataTable menuData, MenuItem parentMenuItem)
{
DataView view = new DataView(menuData);
view.RowFilter = "DepartmentParentID=" + parentMenuItem.Value;
foreach (DataRowView row in view)
{
MenuItem newMenuItem = new MenuItem(row["DepartmentName"].ToString(), row["DepartmentID"].ToString());
parentMenuItem.ChildItems.Add(newMenuItem);
AddChildMenuItems(menuData, newMenuItem);
}
}
private DataTable GetMenuData()
{
using (SqlConnection con = new SqlConnection(conStr))
{
using (SqlCommand cmd = new SqlCommand("SELECT DepartmentID,OfficeID,DepartmentName,DepartmentParentID,IsActive,CreatedByID,CreatedDate,LastModifiedByID,LastModifiedDt FROM DepartmentMst", con))
{
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
return dt;
}
}
}
問題は、AddTopMenuItems() メソッドにあり、Menu1.Items.Add(newMenuItem); 行に「オブジェクト参照がオブジェクトのインスタンスに設定されていません」と表示されます。わからない なぜ?
SQLSERVER2008 DepartmentMst のデータは次のとおりです。
DepartmentID DepartmentName IsActive DepartmentParentID
1 HR 1 NULL
2 IT 1 NULL
3 Operations 1 NULL
4 Desktop Engineer 1 2
5 Network Engineer 1 2
6 Employee Salary 1 1
DepartmentParentID が NULL の場合はメイン メニューであり、null でない場合はその親 ID に関する子ノードです。
サンプルはこちらhttp://chandradev819.wordpress.com/2011/07/03/how-to-bind-asp-net-menu-control-with-database/
助けて感謝!