简体   繁体   中英

Enabling/disabling buttons via function/method

  1. I have 8 buttons, each performs a different task, ie edit, delete, create etc, and a context​Menu for each of the task

  2. I've a table called Moderations in DB, which consists of bools ie groupTitle, canEdit, canDelete, canCreate..... groupTitle is string not bool

  3. I have a bool function canDoIt(task, userid) to check whether the logged in user (which will have specific groupTitle), can perform or can't (function return true or false for provided task, in short)

Suppose, I want to check whether a logged in user can perform the task or not, check via canDoit(task, userid), and If he cannot, the button will be disabled otherwise won't.... OnForm_Load I throw the function (or may be another time when I need it) and check for each button, ie

btnEdit.Enabled = canDo("canEdit", userID)
btnDelete.Enabled = canDo("canDelete", userID)
btnCreate.Enabled = canDo("canCreat", userID)

cnxMenuEdit.Enabled = canDo("canEdit", userID)
cnxMenuDelete.Enabled = canDo("canDelete", userID)
.
.
.
.....and so on and so forth.

My method work fine and good but I have doubts and questions.

First question, is good to be so?

Second question, is it professional?

Another is, will that effect program or database performance?

You need to keep your logged in user's access rights in memory. Create some user model that will contains list of access right, load it to some static object when user logging in and then you can check access when you need.

Something like that

public class UserModel 
{
    public List<UserAccessRight> AccessRights {get; set;}
}

public class UserAccessRight
{
    public string Name {get; set;}
}

public static class SomeAuthHelperClass
{
    public UserModel CurrentUser {get; set;}

    // some helper methods to retrieve data etc.

   public static CanDo(string accessRight)
   {
       return CurrentUser.AccessRights.Contains(ar => ar.Name.Equals(accessRight);
   }
}
.....

btnEdit.Enabled = SomeAuthHelperClass.CanDo("EditSomething");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM