1

I have a MenuStrip in my Windows Form Application which Contains MenuItems.

I want to check some condition and disable the visibility of MenuItems in the MenuStrip bar. Suppose Normal User is accessing the application ,then Some MenuItems will be hidden and if Admin user is accessing the application then all MenuItems should be visible.

This is my code (I'am not sure about it ) which didn't work.

  public Visite(string username)
    {
        InitializeComponent();
        label1.Text = username;

        using (SqlConnection con = new SqlConnection("Data Source=ADMIN-PC\\SQLEXPRESS;Initial Catalog=timar;Integrated Security=True"))
        {
            con.Open();
            bool UserIsAdmin = true;
            using (SqlCommand cmd = new SqlCommand("select * from [User] where Role =@Role", con))
            {
                cmd.Parameters.AddWithValue("@Role", "Admin");

                UserIsAdmin = (int)cmd.ExecuteScalar() > 0;
            }
            if (UserIsAdmin == false)
            {
                utilisateurToolStripMenuItem.Visible = false;
            }
           else
           {
               utilisateurToolStripMenuItem.Visible= true;
            }
           con.Close();
       }

    }

Please help. Thanks in advance.

2 Answers2

0

You are talking about visibility in your question, but your Code says Enabled.

These are two completely different things.

In case you stick with visbility the you should set utilisateurToolStripMenuItem.Visible to false

lokusking
  • 7,396
  • 13
  • 38
  • 57
0

try This..

public Visite(string username)
{
    InitializeComponent();
    label1.Text = username;
    using (SqlConnection con = new SqlConnection("Data Source=ADMIN-PC\\SQLEXPRESS;Initial Catalog=timar;Integrated Security=True"))
    {
        con.Open();
        bool UserIsAdmin = false;
        using (SqlCommand cmd = new SqlCommand("select * from [User] where Role =@Role", con))
        {
            cmd.Parameters.AddWithValue("@Role", "Admin");
            UserIsAdmin = (int)cmd.ExecuteScalar() > 0;
        }
       utilisateurToolStripMenuItem.Visible = UserIsAdmin;
     }
}
Pankaj
  • 2,618
  • 3
  • 25
  • 47