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 th开发者_如何学Goe 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 :-)
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
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.
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
}
精彩评论