CheckedListBox数据绑定及取值技巧

来源:互联网 发布:古玩玉器交友软件 编辑:程序博客网 时间:2024/05/16 16:01
CheckedListBox数据绑定及取值技巧  

 
1、添加项:Items.Add


checkedListBox1.Items.Add("June");
checkedListBox1.Items.Add("Jun");
2、判断第i项是否选中GetItemChecked(index)


checkedListBox1.GetItemChecked(i)
3、设置第i项是否选中SetItemChecked(index,bool)或者SetItemCheckState(index,CheckState)


checkedListBox1.SetItemChecked(index, true);
checkedListBox1.SetItemCheckState(index, CheckState.Unchecked);
4、设置全选


for (int i = 0; i < listBoxLED.Items.Count; i++)
{
    checkedListBox1.SetItemCheckState(i, CheckState.Checked);
    //checkedListBox1.SetItemChecked(i, true);
}
5、数据绑定


CheckedListBox应该是由ListBox扩展而来的,但在使用的时候,可能会发现——它不支持DataSource属性,不能像ListBox那样指定其数据源为一个DataTable。


事实上,CheckedListBox像ListBox一样有DataSource属性,DisplayMember和ValueMemeber属性也都是有的,只是IntelliSense不能将其智能感知出来。


因此,我们可以通过代码将CheckedListBox绑定。


DataSet ds=bll.GetAllStudent();
checkedListBox1.DataSource = ds.Table[0];
checkedListBox1.ValueMember = "student_id";

checkedListBox1.DisplayMember = "student_name";


6、如何获取checkedListBox1选中项的DisplayMember和ValueMember


方法1:

for (int i = 0; i < checkedListBox1.CheckedItems.Count; i++)
{
    DataRowView dv = ((DataRowView)checkedListBox1.CheckedItems[i]);
    string id = dv["student_id"].ToString();
    string name = dv["student_name"].ToString();
}


方法2:


获取Text:获取Text还是很简单,就在CheckedListBox上获取就行.获取选中选中项的Text


string name = checkedListBox1.GetItemText(checkedListBox1.Items[i]);
获取Value的值:这里就用了一个技巧,就是通过绑定到CheckedListBox的DataSet来获取。(在网上看到说是因为在CheckedListBox中获取到的索引Index是与DataSet中相应的值是一样的。知道原因的帮忙解释一下)


string name = ds.Tables[0].Rows[i]["student_name"].ToString();//此处i为CheckedListBox选中项的索引
 

7:  点击复选框选中

CheckOnClick = true



如果大家觉得CheckedListBox哪些知识点比较常用,欢迎补充。
原创粉丝点击