1
public static class CheckedListBox扩展2


{3

/**//// <summary>4
/// 全部选定所有项5
/// </summary>6
public static void 全部选定(this CheckedListBox c)7

{8
for (int i = 0; i < c.Items.Count; i++)9

{10
c.SetItemChecked(i, true);11
}12
}13

14

/**//// <summary>15
/// 全部取消选定所有项16
/// </summary>17
public static void 全部取消选定(this CheckedListBox c)18

{19
for (int i = 0; i < c.Items.Count; i++)20

{21
c.SetItemChecked(i, false);22
}23
}24

25

/**//// <summary>26
/// 反向选定所有项27
/// </summary>28
public static void 反向选定(this CheckedListBox c)29

{30
for (int i = 0; i < c.Items.Count; i++)31

{32
c.SetItemChecked(i, !c.GetItemChecked(i));33
}34
}35

36

/**//// <summary>37
/// 根据选定状态列表中的值,逐一设定各列表项的选定状态38
/// </summary>39
/// <param name="选定状态列表">包含所有列表项对应的选定状态的列表</param>40
public static void 自设选定(this CheckedListBox c, IEnumerable<bool> 选定状态列表)41

{42
int x = 0;43
foreach (bool f in 选定状态列表)44

{45
c.SetItemChecked(x++, f);46
}47
}48

49

/**//// <summary>50
/// 根据选定项索引列表的值,设定指定索引处列表项的选定状态为已选定,其它处均设为未选定51
/// </summary>52
/// <param name="选定项索引列表">包含选定列表项的索引位置的列表</param>53
public static void 自设选定(this CheckedListBox c, IEnumerable<int> 选定项索引列表)54

{55
c.全部取消选定();56
foreach (int f in 选定项索引列表)57

{58
c.SetItemChecked(f, true);59
}60
}61

62

/**//// <summary>63
/// 将一个字典作为数据源加载到CheckedListBox,字典的键即为列表项的值,字典的值用以指示列表项是否被选定64
/// </summary>65
/// <typeparam name="类型">自定义类型</typeparam>66
/// <param name="数据源">数据源</param>67
public static void 数据源设定<类型>(this CheckedListBox c, Dictionary<类型, bool> 数据源)68

{69
var l=数据源.Values.ToArray();70
c.DataSource = null;71
c.DataSource = 数据源.Keys.ToList();72
c.自设选定(数据源.Values);73
}74

75

/**//// <summary>76
/// 将CheckedListBox的列表项及其选定状态作为字典返回,字典的键即为列表项的值,字典的值用以指示列表项是否被选定77
/// </summary>78
/// <typeparam name="类型">自定义类型</typeparam>79
/// <returns>字典</returns>80
public static Dictionary<类型, bool> 数据源获取<类型>(this CheckedListBox c)81

{82
var l = new Dictionary<类型, bool>();83
for (int i = 0; i < c.Items.Count; i++)84

{85
l.Add((类型)c.Items[i], c.GetItemChecked(i));86
}87
return l;88
}89
}该扩展提供了控制、加载、导出CheckedListBox选定状态的一些实用方法。
用于测试加载及导出的代码片段:
private void button2_Click(object sender, EventArgs e)
{
var l = new Dictionary<string, bool>();
l.Add("a", true);
l.Add("q", false);
l.Add("w", true);
l.Add("e", false);
checkedListBox1.数据源设定<string>(l);
}
private void button3_Click(object sender, EventArgs e)
{
checkedListBox2.数据源设定<string>(checkedListBox1.数据源获取<string>());
}