Dynamic Menu : Menu « GUI Windows Form « C# / C Sharp






Dynamic Menu

/*
User Interfaces in C#: Windows Forms and Custom Controls
by Matthew MacDonald

Publisher: Apress
ISBN: 1590590457
*/

using System.Data.SqlClient;

using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;

namespace DynamicMenu
{
    /// <summary>
    /// Summary description for DynamicMenu.
    /// </summary>
    public class DynamicMenu : System.Windows.Forms.Form
    {
        internal System.Windows.Forms.MainMenu mnuMain;
        internal System.Windows.Forms.MenuItem mnuFile;
        internal System.Windows.Forms.MenuItem mnuNew;
        internal System.Windows.Forms.MenuItem mnuOpen;
        internal System.Windows.Forms.MenuItem mnuClose;
        internal System.Windows.Forms.MenuItem mnuSave;
        internal System.Windows.Forms.MenuItem MenuItem12;
        internal System.Windows.Forms.MenuItem mnuExit;
        internal System.Windows.Forms.MenuItem mnuTools;
        internal System.Windows.Forms.MenuItem mnuManageHardware;
        internal System.Windows.Forms.MenuItem mnuSetupUserAccounts;
        internal System.Windows.Forms.MenuItem mnuChangeDisplay;
        internal System.Windows.Forms.MenuItem mnuHelp;
        internal System.Windows.Forms.MenuItem mnuContents;
        internal System.Windows.Forms.MenuItem MenuItem13;
        internal System.Windows.Forms.MenuItem mnuAbout;
        internal System.Windows.Forms.Button cmdAdmin;
        internal System.Windows.Forms.Button cmdUser;
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.Container components = null;

        public DynamicMenu()
        {
            //
            // Required for Windows Form Designer support
            //
            InitializeComponent();

            //
            // TODO: Add any constructor code after InitializeComponent call
            //
        }

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        protected override void Dispose( bool disposing )
        {
            if( disposing )
            {
                if (components != null) 
                {
                    components.Dispose();
                }
            }
            base.Dispose( disposing );
        }

        #region Windows Form Designer generated code
        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.mnuMain = new System.Windows.Forms.MainMenu();
            this.mnuFile = new System.Windows.Forms.MenuItem();
            this.mnuNew = new System.Windows.Forms.MenuItem();
            this.mnuOpen = new System.Windows.Forms.MenuItem();
            this.mnuClose = new System.Windows.Forms.MenuItem();
            this.mnuSave = new System.Windows.Forms.MenuItem();
            this.MenuItem12 = new System.Windows.Forms.MenuItem();
            this.mnuExit = new System.Windows.Forms.MenuItem();
            this.mnuTools = new System.Windows.Forms.MenuItem();
            this.mnuManageHardware = new System.Windows.Forms.MenuItem();
            this.mnuSetupUserAccounts = new System.Windows.Forms.MenuItem();
            this.mnuChangeDisplay = new System.Windows.Forms.MenuItem();
            this.mnuHelp = new System.Windows.Forms.MenuItem();
            this.mnuContents = new System.Windows.Forms.MenuItem();
            this.MenuItem13 = new System.Windows.Forms.MenuItem();
            this.mnuAbout = new System.Windows.Forms.MenuItem();
            this.cmdAdmin = new System.Windows.Forms.Button();
            this.cmdUser = new System.Windows.Forms.Button();
            this.SuspendLayout();
            // 
            // mnuMain
            // 
            this.mnuMain.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
                                                                                    this.mnuFile,
                                                                                    this.mnuTools,
                                                                                    this.mnuHelp});
            // 
            // mnuFile
            // 
            this.mnuFile.Index = 0;
            this.mnuFile.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
                                                                                    this.mnuNew,
                                                                                    this.mnuOpen,
                                                                                    this.mnuClose,
                                                                                    this.mnuSave,
                                                                                    this.MenuItem12,
                                                                                    this.mnuExit});
            this.mnuFile.Text = "File";
            // 
            // mnuNew
            // 
            this.mnuNew.Index = 0;
            this.mnuNew.Text = "New";
            // 
            // mnuOpen
            // 
            this.mnuOpen.Index = 1;
            this.mnuOpen.Text = "Open";
            // 
            // mnuClose
            // 
            this.mnuClose.Index = 2;
            this.mnuClose.Text = "Close";
            // 
            // mnuSave
            // 
            this.mnuSave.Index = 3;
            this.mnuSave.Text = "Save";
            // 
            // MenuItem12
            // 
            this.MenuItem12.Index = 4;
            this.MenuItem12.Text = "-";
            // 
            // mnuExit
            // 
            this.mnuExit.Index = 5;
            this.mnuExit.Text = "Exit";
            // 
            // mnuTools
            // 
            this.mnuTools.Index = 1;
            this.mnuTools.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
                                                                                     this.mnuManageHardware,
                                                                                     this.mnuSetupUserAccounts,
                                                                                     this.mnuChangeDisplay});
            this.mnuTools.Text = "Tools";
            // 
            // mnuManageHardware
            // 
            this.mnuManageHardware.Index = 0;
            this.mnuManageHardware.Text = "Manage Hardware";
            // 
            // mnuSetupUserAccounts
            // 
            this.mnuSetupUserAccounts.Index = 1;
            this.mnuSetupUserAccounts.Text = "Setup User Accounts";
            // 
            // mnuChangeDisplay
            // 
            this.mnuChangeDisplay.Index = 2;
            this.mnuChangeDisplay.Text = "Change Display";
            // 
            // mnuHelp
            // 
            this.mnuHelp.Index = 2;
            this.mnuHelp.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
                                                                                    this.mnuContents,
                                                                                    this.MenuItem13,
                                                                                    this.mnuAbout});
            this.mnuHelp.Text = "Help";
            // 
            // mnuContents
            // 
            this.mnuContents.Index = 0;
            this.mnuContents.Text = "Contents";
            // 
            // MenuItem13
            // 
            this.MenuItem13.Index = 1;
            this.MenuItem13.Text = "-";
            // 
            // mnuAbout
            // 
            this.mnuAbout.Index = 2;
            this.mnuAbout.Text = "About";
            // 
            // cmdAdmin
            // 
            this.cmdAdmin.FlatStyle = System.Windows.Forms.FlatStyle.System;
            this.cmdAdmin.Location = new System.Drawing.Point(132, 88);
            this.cmdAdmin.Name = "cmdAdmin";
            this.cmdAdmin.Size = new System.Drawing.Size(80, 24);
            this.cmdAdmin.TabIndex = 3;
            this.cmdAdmin.Text = "Admin Level";
            this.cmdAdmin.Click += new System.EventHandler(this.cmdAdmin_Click);
            // 
            // cmdUser
            // 
            this.cmdUser.FlatStyle = System.Windows.Forms.FlatStyle.System;
            this.cmdUser.Location = new System.Drawing.Point(44, 88);
            this.cmdUser.Name = "cmdUser";
            this.cmdUser.Size = new System.Drawing.Size(80, 24);
            this.cmdUser.TabIndex = 2;
            this.cmdUser.Text = "User Level";
            this.cmdUser.Click += new System.EventHandler(this.cmdUser_Click);
            // 
            // DynamicMenu
            // 
            this.AutoScaleBaseSize = new System.Drawing.Size(5, 14);
            this.ClientSize = new System.Drawing.Size(256, 129);
            this.Controls.AddRange(new System.Windows.Forms.Control[] {
                                                                          this.cmdAdmin,
                                                                          this.cmdUser});
            this.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
            this.Menu = this.mnuMain;
            this.Name = "DynamicMenu";
            this.Text = "Dynamic Menu";
            this.Load += new System.EventHandler(this.DynamicMenu_Load);
            this.ResumeLayout(false);

        }
        #endregion

        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main() 
        {
            Application.Run(new DynamicMenu());
        }

        private void DynamicMenu_Load(object sender, System.EventArgs e)
        {
            cmdUser_Click(null,null);

        }

        private void cmdUser_Click(object sender, System.EventArgs e)
        {
            DataTable dtPermissions;

            // Get permissions for an Admin-level user.
            dtPermissions = DBPermissions.GetPermissions(DBPermissions.Level.User);

            // Update the menu with these permissions.
            SearchMenu(this.Menu, dtPermissions);

        }

        private void cmdAdmin_Click(object sender, System.EventArgs e)
        {
            DataTable dtPermissions;

            // Get permissions for an Admin-level user.
            dtPermissions = DBPermissions.GetPermissions(DBPermissions.Level.Admin);

            // Update the menu with these permissions.
            SearchMenu(this.Menu, dtPermissions);

        }

        private void SearchMenu(Menu menu, DataTable dtPermissions)
        {
            DataRow[] rowMatch;

            foreach (MenuItem mnuItem in menu.MenuItems)
            {           
                // See if this menu item has a corresponding row.
                rowMatch = dtPermissions.Select("ControlName = '" + mnuItem.Text + "'");

                // If it does, configure the menu item state accordingly.           
                if (rowMatch.GetLength(0) > 0)
                {
                    DBPermissions.State state;
                    state = (DBPermissions.State)int.Parse(rowMatch[0]["State"].ToString());

                    switch (state)
                    {
                        case DBPermissions.State.Hidden:
                            mnuItem.Visible = false;
                            break;
                        case DBPermissions.State.Disabled:
                            mnuItem.Enabled = false;
                            break;
                    }
                }
                else
                {
                    mnuItem.Visible = true;
                    mnuItem.Enabled = true;
                }

                // Search recursively through any submenus.
                if (mnuItem.MenuItems.Count > 0)
                {
                    SearchMenu(mnuItem, dtPermissions);
                }
            }
        }

    }
    public class DBPermissions
    {
        public enum State
        {
            Normal = 0,
            Disabled = 1,
            Hidden = 2
        }

        public enum Level
        {
            Admin,
            User
        }

        private static SqlConnection con = new SqlConnection("Data Source=localhost;"
            + "Integrated Security=SSPI;Initial Catalog=Apress;");

        public static DataTable GetPermissions(Level userLevel)
        {
            con.Open();

            // Permissions isn't actually actually a table in our data source.
            // Instead, it's a view that combines the important information
            // from all three tables using a Join query.
            string selectPermissions = "SELECT * FROM Permissions ";

            switch (userLevel)
            {
                case Level.Admin:
                    selectPermissions += "WHERE LevelName = 'Admin'";
                    break;
                case Level.User:
                    selectPermissions += "WHERE LevelName = 'User'";
                    break;
            }

            SqlCommand cmd = new SqlCommand(selectPermissions, con);
            SqlDataAdapter adapter = new SqlDataAdapter(cmd);
            DataSet ds = new DataSet();
            adapter.Fill(ds, "Permissions");

            con.Close();

            return ds.Tables["Permissions"];
        }
    }

}
/*
-- Database Dump Wizard Ver 2.2.1 (libmssql version 2.3)
--
-- Host: localhost    Database: [Apress]
-- ---------------------------------------------------------
-- Server version   Microsoft SQL Server Version 8.0.255


-- Dumping user-defined datatypes in '[Apress]'


-- Table structure for table 'Controls'
CREATE TABLE [Controls] (
[ID] int IDENTITY NOT NULL,
[ControlName] varchar(20) NOT NULL)
GO

CREATE UNIQUE CLUSTERED INDEX PK_Controls ON [Controls] (ID)
GO


-- Dumping data for table 'Controls'
--

-- Enable identity insert
SET IDENTITY_INSERT [Controls] ON
GO

INSERT INTO [Controls] ([ID], [ControlName])
VALUES(1, 'New')
GO
INSERT INTO [Controls] ([ID], [ControlName])
VALUES(2, 'Save')
GO
INSERT INTO [Controls] ([ID], [ControlName])
VALUES(3, 'Manage Hardware')
GO
INSERT INTO [Controls] ([ID], [ControlName])
VALUES(4, 'Setup User Accounts')
GO

-- Disable identity insert
SET IDENTITY_INSERT [Controls] OFF
GO



-- Table structure for table 'Controls_Levels'
CREATE TABLE [Controls_Levels] (
[ID] int IDENTITY NOT NULL,
[Control_ID] int NOT NULL,
[Level_ID] int NOT NULL,
[State] smallint)
GO

CREATE UNIQUE CLUSTERED INDEX PK_Control_Levels ON [Controls_Levels] (ID)
GO


-- Dumping data for table 'Controls_Levels'
--

-- Enable identity insert
SET IDENTITY_INSERT [Controls_Levels] ON
GO

INSERT INTO [Controls_Levels] ([ID], [Control_ID], [Level_ID], [State])
VALUES(1, 1, 2, 1)
GO
INSERT INTO [Controls_Levels] ([ID], [Control_ID], [Level_ID], [State])
VALUES(2, 2, 2, 1)
GO
INSERT INTO [Controls_Levels] ([ID], [Control_ID], [Level_ID], [State])
VALUES(3, 3, 2, 2)
GO
INSERT INTO [Controls_Levels] ([ID], [Control_ID], [Level_ID], [State])
VALUES(4, 4, 2, 2)
GO

-- Disable identity insert
SET IDENTITY_INSERT [Controls_Levels] OFF
GO



-- Table structure for table 'Levels'
CREATE TABLE [Levels] (
[ID] int IDENTITY NOT NULL,
[LevelName] varchar(50))
GO

CREATE UNIQUE CLUSTERED INDEX PK_UserLevels ON [Levels] (ID)
GO


-- Dumping data for table 'Levels'
--

-- Enable identity insert
SET IDENTITY_INSERT [Levels] ON
GO

INSERT INTO [Levels] ([ID], [LevelName])
VALUES(1, 'Admin')
GO
INSERT INTO [Levels] ([ID], [LevelName])
VALUES(2, 'User')
GO

-- Disable identity insert
SET IDENTITY_INSERT [Levels] OFF
GO


CREATE VIEW [Permissions]
AS
SELECT     Controls.ControlName, Levels.LevelName, Controls_Levels.State
FROM         Controls INNER JOIN
                      Controls_Levels ON Controls.ID = Controls_Levels.Control_ID INNER JOIN
                      Levels ON Controls_Levels.Level_ID = Levels.ID
GO


*/

           
       








Related examples in the same category

1.Add context menu to a form windowAdd context menu to a form window
2.Build Menu and context sensitive menu on your ownBuild Menu and context sensitive menu on your own
3.Add shortcut key to a menu itemAdd shortcut key to a menu item
4.Form MenuForm Menu
5.Add a Main MenuAdd a Main Menu
6.Menu Text Provider HostMenu Text Provider Host