枚举作为CheckBoxList的数据源
本文关键字:数据源 CheckBoxList 枚举 | 更新日期: 2023-09-27 18:14:26
我创建了enum
对象,如以下
public enum Status
{
Active,
Inactive,
Deleted
}
我想把那些enum
绑定到CheckBoxList。
我试过了,
chkStatus.DataSource = Status;
chkStatus.DataBind();
有可能吗?如果是,如何做到这一点?
try:
public enum Status
{
Active = 0,
Inactive = 1,
Deleted = 2
}
并绑定CheckBoxList
checkboxID.DataSource = Enum.GetNames(typeof(Status));
checkboxID.DataBind();
考虑这个枚举:
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();
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();
希望这个代码片段能对你有所帮助。