0

下面的动态菜单显示来自数据库的数据,但我想为为处理引发的单击事件而创建的子菜单项创建一个事件处理程序。另外请帮助我使用事件处理程序代码来跟踪单击了哪个子菜单(例如,基于子菜单项的值)。

public partial class _Default : System.Web.UI.Page {
    string connect = WebConfigurationManager.ConnectionStrings["con"].ToString();
    SqlConnection con1;

    protected void Page_Load(object sender, EventArgs e) {
        con1 = new SqlConnection(connect);
        con1.Open();
        if (!IsPostBack) {
            PopulateMenuItems();
        } else {
            Label1.Text = Request.QueryString["str"].ToString();
        }
    }

    private void PopulateMenuItems() {
        DataTable dt_GetParentData = GetMenuData_Parent();
        AddTopMenuItems(dt_GetParentData);
    }

    private DataTable GetMenuData_Child() {
        using (SqlCommand cmd = new SqlCommand("SELECT  Department, FirstName + ' ' + LastName as Name FROM Employees", con1)) {
            SqlDataAdapter da_menuchild = new SqlDataAdapter(cmd);
            DataTable dt_menuchild = new DataTable();
            da_menuchild.Fill(dt_menuchild);
            return dt_menuchild;
        }

    }

    private DataTable GetMenuData_Parent() { 
        using(SqlCommand cmd1 = new SqlCommand("SELECT DISTINCT Department FROM Employees", con1)) {
            SqlDataAdapter da_menuparent = new SqlDataAdapter(cmd1);
            DataTable dt_menuparent = new DataTable();
            da_menuparent.Fill(dt_menuparent);
            return dt_menuparent;
        }
    }

    private void AddTopMenuItems(DataTable dt_Parent) {
        DataTable dtchild = GetMenuData_Child();
        DataView parent_view = new DataView(dt_Parent);

        foreach (DataRowView row in parent_view) {
            MenuItem newParentItem = new MenuItem(row["Department"].ToString());
            Menu2.Items.Add(newParentItem);
            AddChildMenuItems(dtchild,newParentItem);
        }
    }

    private void AddChildMenuItems(DataTable dtchild, MenuItem parentitem) {
        string parent = parentitem.Value.ToString();
        DataView childview = new DataView(dtchild);
        childview.RowFilter = String.Format("Department='{0}'", parent);

        foreach(DataRowView row1 in childview) {
            MenuItem newChildItem = new MenuItem(row1["Name"].ToString());
            parentitem.ChildItems.Add(newChildItem);
            newChildItem.NavigateUrl = "Default2.aspx?str=" + newChildItem.Value.ToString();
        }
    }
4

1 回答 1

0

你不会只处理 Menu2.MenuItemClick 事件吗? http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.menu.menuitemclick.aspx

在事件 args 中,您可以访问单击的项目,以便您可以确定用户单击了哪个项目并做出相应的反应。

于 2013-06-25T20:21:05.123 回答