disable button for user login in winforms

ravi kumar 331 Reputation points
2020-12-22T04:38:49.41+00:00

in my winform application , i have 3 forms ,

Login form
Main form
Data entry form
when the login is "User" , Main form should open , but in the childform "data entry" - "button1" should be disabled. when the login is "Admin" , Main form should open , but in the childform "data entry" - "button1" should be enabled.

i tried with below code , but the button1 is working no matter who is logged on , kindly guide me how to achieve this:

private void btnlogin_Click(object sender, EventArgs e)  
        {  
            if(cmbusername.Text != "" && txtpassword.Text != "")  
            {  
                SqlConnection con = new SqlConnection(cs);  
                string query = "select * from login where username = @user and password = @pass";  
                SqlCommand cmd = new SqlCommand(query, con);  
                cmd.Parameters.AddWithValue("@user", cmbusername.Text);  
                cmd.Parameters.AddWithValue("@pass", txtpassword.Text);  
  
                con.Open();  
  
                SqlDataReader dr = cmd.ExecuteReader();  
                if (dr.HasRows == true)  
                {  
                    if(cmbusername.Text == "USER")  
                    {  
                        FormDataEntry frmd = new FormDataEntry();  
                        frmd.button1.Enabled = false;  
                    }  
                    else if(cmbusername.Text == "ADMIN")  
                    {  
                        FormDataEntry frmd = new FormDataEntry();  
                        frmd.button1.Enabled = true;  
                    }  
                    this.Hide();  
                    FrmMain FrmMain = new FrmMain();  
                    FrmMain.Show();  
                }  
                else  
                {  
                    MessageBox.Show("Login Failed");  
                }  
  
                con.Close();  
            }  
            else  
            {  
                MessageBox.Show("Please fill in both fields");  
            }  
              
        }  

I have added the pics of my app in sequence

  1. First login form will open
  2. Next dahsboard(formMain) will open for both of the "User" & "Admin"
  3. Next when the "initial data entry" is clicked on the left side menu , a child form(formdataentry) will open , in this i need to disable delete button if the login is as user.

50323-login-form.png50324-main-form-or-dshboard.png50254-data-entry-form.png

Windows Forms
Windows Forms
A set of .NET Framework managed libraries for developing graphical user interfaces.
1,835 questions
Visual Studio
Visual Studio
A family of Microsoft suites of integrated development tools for building applications for Windows, the web and mobile devices.
4,628 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,278 questions
0 comments No comments
{count} votes

Accepted answer
  1. YASER SHADMEHR 781 Reputation points
    2020-12-22T22:21:26.987+00:00

    Frmd has been created a limited scope, e.g. it has been created in line 18 and it dies at line 20! You need to create at the upper scope and just set enable there. Also, you need to keep the reference to frmd object by FrmMain:

    private void btnlogin_Click(object sender, EventArgs e)
    {
        if(cmbusername.Text != "" && txtpassword.Text != "")
        {
            // Your code
    
             if (dr.HasRows == true)
             {
                 FormDataEntry frmd = new FormDataEntry();
                 if(cmbusername.Text == "USER")
                 {
                     frmd.button1.Enabled = false;
                 }
                     else if(cmbusername.Text == "ADMIN")
                 {
                     frmd.button1.Enabled = true;
                 }
    
                 this.Hide();
                 FrmMain FrmMain = new FrmMain();
    
                 //Keep a reference to frmd obj though FrmMain, otherwise you will lose it
                 // If is MDI relation: frmd.MdiParent = FrmMain;
                 // If not, something like this: FrmMain.DataEntryForm = frmd.
    
                 FrmMain.Show();
             } 
    
             // the rest of your code 
    }
    

    My Suggestion:

    creating a singleton class for the user and use this class inside FormDataEntry & FrmMain classes:

    public class User
    {
        public bool IsAdmin { get; set; }
        public bool IsUser { get; set; }
    
        private static User _currentUser;
    
        private static object _locker = new object(); // Remove this if you don't need to support multi-thread.
        public static User CurrentUser
        {
            get
            {
                // Returns _currentUser, if it has been create before
                if (_currentUser != null) return _currentUser;
    
                // lock all threads and let them go inside lock one by one
                lock (_locker)
                {
                    // Double-checked locking: This will prevent multi-time creation of _currentUser. 
                    // e.g. two threads came together for the first time and wait in the lock(_locker).
                    if (_currentUser == null)
                    {
                        _currentUser = new User();
                    }
                    return _currentUser;
                }
            }
        }
    }
    

    Then btnlogin_Click will like this:

        private void btnlogin_Click(object sender, EventArgs e)
        {
            if(cmbusername.Text != "" && txtpassword.Text != "")
            {
                // Your code
    
                 if (dr.HasRows == true)
                 {
                     User.CurrentUser.IsUser= cmbusername.Text == "USER";
                     User.CurrentUser.IsAdmin = cmbusername.Text == "ADMIN";
    
                     this.Hide();
                     FrmMain FrmMain = new FrmMain();
                     FrmMain.Show();
                 } 
    
                 // the rest of your code 
        }
    

    Then, use User in FormDataEntry form loading event:

    private void FormDataEntry_Load(object sender, EventArgs e)
    {
        button1.Enabled = User.CurrentUser.IsAdmin;
    }
    

1 additional answer

Sort by: Most helpful
  1. Karen Payne MVP 35,191 Reputation points
    2020-12-23T03:52:51.26+00:00

    Hello @ravi kumar

    I have a robust code sample but being robust means it's not a simple copy and paste solution. If you want a simple solution stop here but if you want to do it right continue.

    All is explained in the following Microsoft TechNet article.

    Details

    • There is a table for users and roles which when used in the application provides fine control over a login and checking roles e.g. user or admin.
    • Each user is created in the database with permissions set.
    • When validating a login user name and password work againsts the last bullet.
    • When doing the login user name and password are encrypted then decrypted when there is a need to use them against the database.
    • The following script creates the database, users and permissions to the database.
    • Frontend project
    • Class project for data operations and login validation
    • Support class project

      Login form

      using System;
      using System.Windows.Forms;
      using LoginLibrary.DataClasses.DataClasses;
      using LoginLibrary.SecurityClasses.SecurityClasses; namespace SqlCredentialLoginInterface
      {
      public partial class LoginForm
      {
      public LoginForm()
      {
      InitializeComponent();
      }
      private void ShowHidePasswordCheckBox_CheckedChanged(object sender, EventArgs e)
      {
      PasswordTextBox.PasswordChar = ShowHidePasswordCheckBox.Checked ? '*' : '\0';
      }
      /// <summary>
      /// Perform login
      /// </summary>
      /// <param name="sender"></param>
      /// <param name="e"></param>
      private void LoginButton_Click(object sender, EventArgs e)
      {
              if (!string.IsNullOrWhiteSpace(UserNameTextBox.Text) && !string.IsNullOrWhiteSpace(PasswordTextBox.Text))  
              {  
      
                  /*  
                   * Change server if not using SQLEXPRESS  
                   */  
                  var ops = new DatabaseUser(".\\SQLEXPRESS", "UserLoginExample");   
      
                  var encryption = new Encryption();  
                  // encrypt user name and password  
                  var userNameBytes = encryption.Encrypt(UserNameTextBox.Text, "111");  
                  var passwordBytes = encryption.Encrypt(PasswordTextBox.Text, "111");  
      
                  var results = ops.SqlCredentialLogin(userNameBytes, passwordBytes);  
      
                  //  
                  // Login recognized (does not know if the user has proper permissions to the tables at this point)  
                  //  
                  if (results.Success)  
                  {  
                      Hide();  
                      var mainForm = new MainForm(userNameBytes, passwordBytes);  
                      mainForm.ShowDialog();  
                  }  
                  else  
                  {  
                      MessageBox.Show(results.Message);  
                  }  
              }  
              else  
              {  
                  MessageBox.Show("Incomplete information to continue.");  
              }  
          }  
          private void CancelButton_Click(object sender, EventArgs e)  
          {  
              Close();  
          }  
      }  
      
      }

      Main form

      using System;
      using System.Linq;
      using System.Windows.Forms;
      using LoginLibrary.DataClasses.DataClasses;
      using LoginLibrary.SupportClasses;
      using SupportLibrary;
      using static SupportLibrary.EnumExtensions; namespace SqlCredentialLoginInterface
      {
      public partial class MainForm
      {
          private readonly byte[] _userNameBytes;  
          private readonly byte[] _userPasswordBytes;  
      
          private readonly BindingSource _productBindingSource = new BindingSource();  
      
          public MainForm(byte[] pNameBytes, byte[] pPasswordBytes)  
          {  
      
              InitializeComponent();  
      
              _userNameBytes = pNameBytes;  
              _userPasswordBytes = pPasswordBytes;  
      
          }  
          private void MainForm_Load(object sender, EventArgs e)  
          {  
      
              var ops = new DataOperations(  
                  _userNameBytes,  
                  _userPasswordBytes,  
                  ".\\SQLEXPRESS",  
                  "UserLoginExample", true);  
      
      
      
              var productTable = ops.ReadProductsByCategory(1);  
              if (ops.IsSuccessFul)  
              {  
      
                  _productBindingSource.DataSource = productTable;  
                  ProductsDataGridView.DataSource = _productBindingSource;  
      
                  var controls = this.ButtonList();  
      
                  Text = ops.User.Name;  
                  if (ops.User.RoleType == RoleTypes.Admin)  
                  {  
                      controls.ForEach(b => b.Enabled = true);  
                  }  
                  else  
                  {  
                      controls.Where(b => EnumParser<RoleTypes>(b.Tag.ToString()) == RoleTypes.User)  
                          .ToList().ForEach(b => b.Enabled = true);  
                  }  
              }  
              else  
              {  
                  MessageBox.Show($"Encountered issues: {ops.LastExceptionMessage}");  
              }  
      
          }  
          private void MainFormClosed(object sender, FormClosedEventArgs e)  
          {  
              Application.ExitThread();  
          }  
      }  
      
      }

      Login form

    50579-a1.png

    Main form

    If a user is not an admin all three buttons are enabled while for a user button2 is enable while the other two are disabled otherwise all three are enabled.

    50661-a1a.png

    User table and role table

    50653-000.png

    50671-1111.png

    0 comments No comments