Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use TinyInt to hide/show controls?

I have 6 buttons on my GUI. The visibility of the buttons can be configured via checkboxes. Checking the checkbox and saving means the correpsonding button should be shown. I am wondering if it is somehow possible to have one TinyInt column in the database which represents the visibility of all 6 buttons.

I created an enum for the buttons, it looks like that:

public enum MyButtons
{
    Button1 = 1,
    Button2 = 2,
    Button3 = 3,
    Button4 = 4,
    Button5 = 5,
    Button6 = 6
}

Now I am wondering how to say that for example only button1, button5 and button6 are checked using this one column. Possible at all?

Thanks :-)

like image 910
grady Avatar asked May 25 '10 10:05

grady


3 Answers

Use a flags enum instead:

[Flags]
public enum MyButtons
{
    None = 0
    Button1 = 1,
    Button2 = 2,
    Button3 = 4,
    Button4 = 8,
    Button5 = 16,
    Button6 = 32
}

Then any combination of buttons is also a unique value - e.g. Button 1 & Button3 == 5

When setting the value use the binary 'or' operator (|):

MyButtons SelectedButtons = MyButtons.Button1 | MyButtons.Button3

To find out if a button is selected use the binary 'and' operator (&):

if (SelectedButtons & MyButtons.Button1 == MyButtons.Button1)... 

The reason this works becomes obvious when you think of the binary representations of the numbers:

MyButtons.Button1 = 000001
MyButtons.Button3 = 000100

When you 'or' them together you get

SelectedButtons = 000001 | 000100 = 000101

When you 'and' that with MyButtons.Button1 - you get back to MyButtons.Button1:

IsButton1Selected = 000101 & 000001 = 000001
like image 150
Martin Harris Avatar answered Nov 16 '22 23:11

Martin Harris


You have to flag your enum with FlagsAttribute:

[Flags]
public enum MyButtons : byte
{
    None = 0
    Button1 = 1,
    Button2 = 1 << 1, 
    Button3 = 1 << 2, 
    Button4 = 1 << 3, 
    Button5 = 1 << 4,
    Button6 = 1 << 5
}

so you can use:

var mode = MyButtons.Button1 | MyButtons.Button5 | MyButtons.Button6;

<< means 'left-shift operator' - just a little bit more easy way to set values to enum items.

like image 39
abatishchev Avatar answered Nov 16 '22 23:11

abatishchev


Add the FlagsAttribute, and derive the enum from byte:

class Program {
    static void Main(string[] args) {
        MyButtons buttonsVisible = MyButtons.Button1 | MyButtons.Button2;
        buttonsVisible |= MyButtons.Button8;

        byte buttonByte = (byte)buttonsVisible; // store this into database

        buttonsVisible = (MyButtons)buttonByte; // retreive from database
    }
}

[Flags]
public enum MyButtons : byte {
    Button1 = 1,
    Button2 = 1 << 1,
    Button3 = 1 << 2,
    Button4 = 1 << 3,
    Button5 = 1 << 4,
    Button6 = 1 << 5,
    Button7 = 1 << 6,
    Button8 = 1 << 7
} 
like image 44
Fredrik Johansson Avatar answered Nov 16 '22 23:11

Fredrik Johansson