事件处理程序中的编码较少?

时间:2012-07-17 05:47:44

标签: c#

任何人都可以建议在c#menustrip中每个菜单项中没有编码的情况下调用流程的更好方法

    private void SetupUserToolStripMenuItem_Click(object sender, EventArgs e)
    {

        UserMenu += "Setup User";
        UserRights=ValidateUser(UserMenu);

        if (UserRights == 1)
        {
            frmDataReader frmDR = new frmDataReader();
            frmDR.Show();
        }
        else
        {

            MessageBox.Show("No Permission");
        }

    private void SetupMasterToolStripMenuItem_Click(object sender, EventArgs e)
    {

        //MessageBox.Show(menuStrip1.  ToolStripMenuItem); 
        UserMenu += "Setup Master";
        UserRights=ValidateUser(UserMenu);

        if (UserRights == 1)
        {
            frmDataReader frmDR = new frmDataReader();
            frmDR.Show();
        }
        else
        {

            MessageBox.Show("No Permission");
        }

2 个答案:

答案 0 :(得分:1)

将相同的事件处理程序附加到所有单击事件,无需为每个按钮编写相同的代码。

答案 1 :(得分:1)

{
    setupMasterToolStripMenuItem.Click += ToolStripMenuItem_Click;
    setupUserToolStripMenuItem.Click += ToolStripMenuItem_Click;
}


ToolStripMenuItem_Click(object sender, EventArgs e)
{
    ToolStripMenuItem toolStripMenuItem = ((ToolStripMenuItem) sender);
    // may be like this
    // or you can check 'setupUser/setupMasterToolStripMenuItem' 
    // is equal to 'toolStripMenuItem' or check 'Tag' of them
    UserMenu += toolStripMenuItem .Text;


    UserRights=ValidateUser(UserMenu);

    if (UserRights == 1)
    {
        frmDataReader frmDR = new frmDataReader();
        frmDR.Show();
    }
    else
    {
        MessageBox.Show("No Permission");
    }
}