如何为子菜单项添加事件处理程序单击事件到以下动态菜单?

时间:2013-06-25 19:49:24

标签: c# asp.net

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

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();
        }
    }

1 个答案:

答案 0 :(得分:0)

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

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