1

我在 ASP.net 中为我的站点主站构建了一个菜单栏:

<div class="MenuBar">
        <asp:ContentPlaceHolder ID="MainContent" runat="server">
            <asp:Menu ID="menuBar" runat="server" Orientation="Vertical" Width="100%">
                <DynamicHoverStyle CssClass="DynamicHover" />
                <DynamicMenuItemStyle CssClass="DynamicMenuItem" />
                <DynamicSelectedStyle CssClass="DynamicHover" />
                <StaticHoverStyle CssClass="staticHover" />
                <StaticMenuItemStyle CssClass="StaticMenuItem" ItemSpacing="1px" />
                <StaticSelectedStyle CssClass="staticHover" />
            </asp:Menu>
        </asp:ContentPlaceHolder>
    </div>

后面的代码:

public partial class SiteMaster : System.Web.UI.MasterPage
{

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        getMenu();
    }
}


private void getMenu()
{
    Menu menuBar = new Menu();
    SqlConnection con = new SqlConnection();
    con.ConnectionString = "server=(local);database=PhilipsMaterials;Integrated Security=SSPI;";
    con.Open();
    DataSet ds = new DataSet();
    DataTable dt = new DataTable();
    string sql = "Select [Material Name] from Materials";
    SqlDataAdapter da = new SqlDataAdapter(sql, con);
    da.Fill(ds);
    dt = ds.Tables[0];
    DataRow[] drowpar = dt.Select();
    String s = "sss";
    foreach (DataRow dr in drowpar)
    {
        menuBar.Items.Add(new MenuItem(dr["Material Name"].ToString()));
    }

    con.Close();

}

}

由于某种原因,当我在浏览器上查看该站点时,菜单未显示。有人知道为什么吗?谢谢。

4

1 回答 1

4

您从菜单实例化一个新对象,然后不要将其添加到现有菜单,您不需要实例化一个新对象,只需将您的功能替换为以下内容:

    private void getMenu()
{
   // Menu menuBar = new Menu();
    SqlConnection con = new SqlConnection();
    con.ConnectionString = "server=(local);database=PhilipsMaterials;Integrated Security=SSPI;";
    con.Open();
    DataSet ds = new DataSet();
    DataTable dt = new DataTable();
    string sql = "Select [Material Name] from Materials";
    SqlDataAdapter da = new SqlDataAdapter(sql, con);
    da.Fill(ds);
    dt = ds.Tables[0];
    DataRow[] drowpar = dt.Select();
    String s = "sss";
    foreach (DataRow dr in drowpar)
    {
        menuBar.Items.Add(new MenuItem(dr["Material Name"].ToString()));
    }

    con.Close();

}
}

并从Page_PreRender而不是从 Page_Load调用它。

于 2012-11-05T11:09:39.197 回答