本文从6各方面对c#checklistbox用法做详细介绍,他们分别是c#checklistbox的用法的添加项、判断第0项是否选中、设置第0项是否选中、设置全选、得到全部选中的值、数据绑定。
1、c#checklistbox用法之添加项:
- checkedListBox1.Items.Add( "蓝色" );
- checkedListBox1.Items.Add( "红色" );
- checkedListBox1.Items.Add( "黄色" );
2、c#checklistbox用法之判断第0项是否选中
- if (checkedListBox1.GetItemChecked(0))
3、c#checklistbox用法之设置第0项是否选中
- checkedListBox1.SetItemChecked(0, true );
4、c#checklistbox用法之设置全选
添加一名为select_all的checkbox控件
- private void select_all_CheckedChanged( object sender, EventArgs e)
- {
- if (select_all.Checked)
- for ( int j = 0; j < checkedListBox1.Items.Count; j++)
- checkedListBox1.SetItemChecked(j, true );
- else
- for ( int j =0; j < checkedListBox1.Items.Count; j++)
- checkedListBox1.SetItemChecked(j, false );
- }
5、c#checklistbox用法之得到全部选中的值:
- private void linkLabel_yes_LinkClicked( object sender, LinkLabelLinkClickedEventArgs e)
- {
- panel_friend.Visible = false ;
- button_friend.Text = "好友面板" ;
- sms_str = null ;
- for ( int j = 0; j < checkedListBox1.Items.Count; j++)
- if (checkedListBox1.GetItemChecked(j))
- {
- //do
- }
- }
6、c#checklistbox用法之数据绑定
- protected void Page_Load( object sender, EventArgs e)
- {
- if (!Page.IsPostBack) //这句很重要,如果不加,则每次加载时都要执行一次绑定,易丢失数据.
- {
- //创建链接;
- SqlConnection con = DB.createConnection(); //不再用 new
- con.Open();
- SqlCommand cmd = new SqlCommand( "select * from [personlike]" ,con);
- SqlDataReader sdr = cmd.ExecuteReader();
- this .CheckBoxList1.DataTextField = "likeContent" ;
- this .CheckBoxList1.DataValueField = "ID" ;
- this .CheckBoxList1.DataSource = sdr;
- this .CheckBoxList1.DataBind();
- sdr.Close(); //关闭记录集
- con.Close(); //关闭链接
- }
- }
- //单击按钮读取所做的操作(数据),用Response.Write()方法显示.
- protected void Button1_Click( object sender, EventArgs e)
- {
- for ( int i=0;i<= this .CheckBoxList1.Items.Count-1;i++)
- {
- if ( this .CheckBoxList1.Items[i].Selected)
- {
- Response.Write( this .CheckBoxList1.Items[i].Value.ToString() + "-" + this .CheckBoxList1.Items[i].Text + " " );
- }
- }
- }
![](http://www.isstudy.com/uploads/allimg/090827/1_090827095906_1.gif)
![](http://www.isstudy.com/uploads/allimg/090827/1_090827095919_1.gif)
![](http://www.isstudy.com/uploads/allimg/090827/1_090827095935_1.gif)