2010-05-25 84 views
5

我有我的GUI 6個按鈕。按鈕的可見性可以通過複選框進行配置。選中複選框並保存意味着應該顯示相關性按鈕。我想知道,如果它在某種程度上可以的,其中代表所有6個按鈕的可見性的數據庫有一個TINYINT列。使用TINYINT隱藏/顯示控件?

我創建了一個枚舉的按鈕,它看起來就像是:

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

現在我想知道怎麼說,例如僅按鈕1,button5和button6使用這一個柱檢驗。有可能嗎?

由於:-)

+0

爲什麼不接受馬丁的答案嗎? – abatishchev 2010-05-25 16:55:29

回答

1

添加的FlagsAttribute,並從中字節枚舉:

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 
} 
+0

還有一件事:我從數據庫中檢索到數據後,如何知道什麼是1,什麼是0? - >找到解決方案...查看Martin Harris的帖子:) – grady 2010-05-25 16:27:54

6

使用一個標誌枚舉代替:

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

然後按鈕的任何組合也是唯一的值 - 例如按鈕1 &將Button3 == 5

當設置值使用二進制「或」運算符(|):

MyButtons SelectedButtons = MyButtons.Button1 | MyButtons.Button3 

要找出是否一個按鈕被選擇使用二進制「和」操作員(& ):

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

當你想到這些數字的二進制表示的這部作品的原因是顯而易見的:

MyButtons.Button1 = 000001 
MyButtons.Button3 = 000100 

當你「或」在一起你

SelectedButtons = 000001 | 000100 = 000101 

當你「和」與MyButtons.Button1 - 你回到MyButtons.Button1:

IsButton1Selected = 000101 & 000001 = 000001 
+0

聽起來不錯,我該怎麼辦儲蓄?我的意思是,該列是TINYINT,如何將所有的按鈕之前,我救他們? – grady 2010-05-25 10:32:35

+0

MSDN推薦下一步:使用None作爲枚舉常量的值爲零的名稱.. http://msdn.microsoft.com/ru-ru/library/system.flagsattribute.aspx – abatishchev 2010-05-25 10:34:45

+1

一旦你有了SelectedButtons值,只需將其轉換爲int並將其保存到數據庫即可。當您將其從數據庫中取出時,將其轉換回MyButtons枚舉值。有一些靜態方法可以在Enum類上執行此操作(http://msdn.microsoft.com/en-us/library/system.enum_members.aspx) – 2010-05-25 10:36:21

3

你必須標記你枚舉與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 
} 

所以你可以使用:

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

<<手段「左移位運算符」 - 只是一點點,更簡單的方式來設定值來枚舉項目。