2014-07-24 74 views
1

我創建enum對象像下面枚舉作爲數據源爲CheckBoxList的

public enum Status 
{ 
    Active, 
    Inactive, 
    Deleted 
} 

我要綁定的enum到CheckBoxList的。

我試過,

chkStatus.DataSource = Status; 
chkStatus.DataBind(); 

這可能嗎?如果是這樣,該怎麼做?

回答

3

嘗試:

public enum Status 
    { 
     Active = 0, 
     Inactive = 1, 
     Deleted = 2 
    } 

並綁定CheckBoxList的

checkboxID.DataSource = Enum.GetNames(typeof(Status)); 
checkboxID.DataBind(); 
+0

因爲我有一些問題,我不能夠嘗試這個......但我仍想知道如何分配'DataTextField'和'DataValueField'?而且我不需要'0,1和2'。 – Jesuraja

0
Dictionary<Status, string> dict = new Dictionary<Status, string>(); 
dct.Add(Status.Active, "Active"); 
dct.Add(Status.Inactive, "Inactive"); 
dct.Add(Status.Deleted, "Deleted"); 

BindingSource src = new BindingSource(); 
src.Datasource = dict; 

((ListBox)YourCheckList).ValueMember = "key"; 
((ListBox)YourCheckList).DisplayMember = "value; 
((ListBox)YourCheckList).Datasource = src; 
((ListBox)YourCheckList).DataBind(); 

希望此代碼段會幫助你。

2

鑑於此枚舉:

public enum Status 
{ 
    Active=1, 
    Inactive=2, 
    Deleted=3 
} 

然後,你可以這樣做:

yourCheckBoxList.DataSource= Enum 
     .GetValues(typeof(Status)) 
     .Cast<Status>() 
     .Select (s =>new KeyValuePair<int,string>((int)s,s.ToString())) 
     .ToList(); 

yourCheckBoxList.DataValueField="Key"; 
yourCheckBoxList.DataTextField="Value"; 
yourCheckBoxList.DataBind();