我在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();
}
}
由于某种原因,当我在浏览器上查看网站时,没有显示菜单。 有人知道为什么吗? 感谢。
答案 0 :(得分:3)
您从菜单中实例化一个新对象,然后不将其分配给现有菜单,您不需要实例化一个新对象,只需将您的函数替换为以下:
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调用。