- 常用操作
- 摘录
- 1. 添加项
- 2. 判断第i项是否选中,选中为true,否则为false
- 3. 设置第i项是否选中
- 4. 设置全选
- 5. 得到全部选中的值,并将选中的项的文本组合成为一个字符串.
- 6. 设置CheckedListBox中第i项的Checked状态
- 7. 全选
- 8. checkedListBox 单选设置(代码实现)
- 9. checkedListBox1显示一个数据库中关键字对应的所有记录
- 10.
- 11. 清除checkedListBox1中所有的选项
- 12. 设置索引为index的项为选中状态
- 13.
- 14. 选中checkedListBox1所有的选项
- 15.
- 16. 反向选择checkedListBox1的选项
- 17. checkedListBox1中选定的项->checkedListBox2
- 18. 绑定数据
- 19.
- 20.
- 问题">问题
最近用到checklistbox控件,在使用其过程中,花了较多的时间,这里我收集了其相关的代码段,希望对大家有所帮助。
常用操作
1. 自定义数据
这种方法是绑定已经给定(自定义)的字段(这种方法是绑定给定的值,就是在编写控件时给Text赋的值): 前台代码:后台代码:
<asp:CheckBoxList ID="CheckBoxList1" runat="server"><asp:ListItem Text ="苹果"></asp:ListItem><asp:ListItem Text ="柠檬"></asp:ListItem><asp:ListItem Text ="橘子"></asp:ListItem><asp:ListItem Text ="桃子"></asp:ListItem></asp:CheckBoxList><asp:Button ID="Button1" runat="server" Text="结果" OnClick ="Button1_Click"/><asp:Label ID="Label1" runat="server" Text=""></asp:Label>
最终效果:
/// <summary>/// Button单击事件/// </summary>/// <param name="sender"></param>/// <param name="e"></param>protected void Button1_Click(object sender, EventArgs e){string s = string.Empty;for (int i = 0; i < this.CheckBoxList1.Items.Count; i++){if (this.CheckBoxList1.Items[i].Selected){s += this.CheckBoxList1.Items[i].Text + " ";}}this.Label1.Text = "你选择的水果有:" + s;}

2. 绑定数据库数据
建立的表:
CheckBoxList控件,如果要是在后台代码之中绑定数据,那么在前台代码做任何修改。 其中,AutoPostBack要为true才可。 后台代码: 后台之中Page_load中的代码(代码初始化,用于打开界面是就进行数据绑定):
<asp:CheckBoxList ID="CheckBoxList1" runat="server" AutoPostBack ="true"></asp:CheckBoxList><asp:Button ID="Button1" runat="server" Text="结果" OnClick ="Button1_Click"/><br /><br /><asp:Label ID="Label1" runat="server" Text=""></asp:Label>
其中,检查网页是否会发很重要。if (!IsPostBack)。如果没有这个,将无法使用。 后台之中Button(结果)按钮:
protected void Page_Load(object sender, EventArgs e){if (!IsPostBack)/* 为什么判断IsPostBack:当你需要执行一些仅需要在页面第一次浏览时执行的事件* 比如页面初始化,数据绑定之类的操作时,需要将操作放在if(!IspostBack)里面,* 这样当你在点击页面中的按钮或者执行其他回发事件时,不贵再次初搜索始化或者* 重复绑定数据,提高了执行效率。*/{string connectionString = ConfigurationManager.ConnectionStrings["connectionString"].ConnectionString;SqlConnection connection = new SqlConnection(connectionString);connection.Open();string sql = "SELECT * FROM KK";SqlCommand cmd = new SqlCommand(sql, connection);SqlDataReader sdr = cmd.ExecuteReader();//任意给的字段名,只要是想显示在界面上的就行。其值给了:Textthis.CheckBoxList1.DataTextField = "name";//任意给得字段名,只要是想在后台看到前台看不到的数据就行。其值给了:Valuethis.CheckBoxList1.DataValueField = "id";this.CheckBoxList1.DataSource = sdr;this.CheckBoxList1.DataBind();sdr.Close();connection.Close();}}
最终运行效果:
/// <summary>/// Button单击事件/// </summary>/// <param name="sender"></param>/// <param name="e"></param>protected void Button1_Click(object sender, EventArgs e){string s = string.Empty;for (int i = 0; i < CheckBoxList1.Items.Count; i++){if (this.CheckBoxList1.Items[i].Selected){s += " 界面上能看到的值(对应控上的Text属性): "+ this.CheckBoxList1.Items[i].Text.ToString()+ "<br/>界面上看不到的值,源程序中能看到(对应控件上的Value属性):"+ this.CheckBoxList1.Items[i].Value.ToString() + "<br/><br/>";}}this.Label1.Text = s;}

3. 全选,取消全选
首先要在前台中加一个CheckBox控件,用来控制是否全选:下划线标注的代码就是添加的CheckBox控件,用来决定是否全选。其中OnCheckedChange事件决定当选择改变时执行什么代码。 其中,设置:AutoPostBack =”true” 很重要。 后台代码(checkbox1_CheckedChanged1事件):
<asp:CheckBoxList ID="CheckBoxList1" runat="server" AutoPostBack ="true"></asp:CheckBoxList><br /><br /><asp:CheckBox ID ="checkbox1" runat ="server" Text ="全选" AutoPostBack ="true" OnCheckedChanged ="checkbox1_CheckedChanged1"/><asp:Button ID="Button1" runat="server" Text="结果" OnClick ="Button1_Click"/><br /><br /><asp:Label ID="Label1" runat="server" Text=""></asp:Label>
最终执行效果: 选中:
/// <summary>/// checkbox1_CheckedChanged1当选择改变时执行相应的代码/// </summary>/// <param name="sender"></param>/// <param name="e"></param>protected void checkbox1_CheckedChanged1(object sender, EventArgs e){if (this.checkbox1.Checked){for (int j = 0; j < this.CheckBoxList1.Items.Count; j++){this.CheckBoxList1.Items[j].Selected = true;//全部设置为选中}}else{for (int k = 0; k < this.CheckBoxList1.Items.Count; k++){this.CheckBoxList1.Items[k].Selected = false;//全部设置为未选中}


4. 获得CheckBox的选中值
4.1 C#获取
//第一种:获得CheckBox的选中值string save_cblJL = "";for (int i = 0; i < this.cblJL.Items.Count; i++){if (this.cblJL.Items[i].Selected == true){save_cblJL += this.cblJL.Items[i].Value + ",";}}//第二种:获得CheckBox的选中值string str_Save_cblJL = "";foreach (ListItem li in cblJL.Items){if (li.Selected == true){str_Save_cblJL += li.Value + ",";}}
4.2 Js获取
- 通过item的Attributes
主要是通过DataBound的时候设置item的Attributes 前台页面代码:
protected void Page_Load(object sender, EventArgs e){IList<test> testList = new List<test>();for (int i = 0; i < 10; i++) {test t = new test();t.Name = "name"+i;t.Code = "code" + i;testList.Add(t);CheckBoxList1.DataSource = testList;CheckBoxList1.DataTextField = "name";CheckBoxList1.DataValueField = "code";CheckBoxList1.DataBind();}}protected void CheckBoxList1_DataBound(object sender, EventArgs e){foreach (ListItem item in CheckBoxList1.Items){item.Attributes["valueCode"] = item.Value;}}
Js代码:
<asp:CheckBoxList ID="CheckBoxList1" runat="server" OnDataBound="CheckBoxList1_DataBound"></asp:CheckBoxList><input id="Button1" type="button" value="button" onclick="getCheckValue();" />
主要是通过获取所选中项的前一个元素的属性valueCode,就是在后台代码中添加item的属性 以下是本文的效果图:
<script type="text/javascript" language="javascript">function getCheckValue() {var chkObject = document.getElementById("CheckBoxList1");var chkInput = chkObject.getElementsByTagName("input");var item="";for (var i = 0; i < chkInput.length; i++) {if (chkInput[i].checked) {item += chkInput[i].parentNode.valueCode + ",";}}alert(item);}</script>

- 通过innerText
<script type="text/javascript" language="javascript">function getCheckValue() {var chkObject = document.getElementById("CheckBoxList1");var chkInput = chkObject.getElementsByTagName("input");var item="";for (var i = 0; i < chkInput.length; i++) {if (chkInput[i].checked) {item += chkInput[i].parentNode.childNodes[1].innerText + ",";}}alert(item);}</script>
这里的<font style="color:rgb(56, 58, 66);background-color:rgb(250, 250, 250);">.childNodes[</font><font style="color:rgb(152, 104, 1);background-color:rgb(250, 250, 250);">1</font><font style="color:rgb(56, 58, 66);background-color:rgb(250, 250, 250);">].innerText</font>可以打印parentNode看看需要的数据在那个节点,一般都是<font style="color:rgb(56, 58, 66);background-color:rgb(250, 250, 250);">childNodes[</font><font style="color:rgb(152, 104, 1);background-color:rgb(250, 250, 250);">1</font><font style="color:rgb(56, 58, 66);background-color:rgb(250, 250, 250);">]</font>。
- 与第二种方法相似,但是用了双层for循环,不推荐。
var v = new Array();var CheckBoxList = document.getElementById("chose_courses_cbl");for (i = 0; i < CheckBoxList.rows.length; i++)for (j = 0; j < CheckBoxList.rows[i].cells.length; j++)if (CheckBoxList.rows[i].cells[j].childNodes[0])if (CheckBoxList.rows[i].cells[j].childNodes[0].checked == true)v.push(CheckBoxList.rows[i].cells[j].childNodes[1].innerText);document.getElementById("courses").value = v;document.getElementById("form1").submit();
5. CheckBoxList赋值
foreach (string str in split){for (int i = 0; i < CheckBoxList1.Items.Count; i++){if (CheckBoxList1.Items[i].Text == str){CheckBoxList1.Items[i].Selected = true;}}}
6. 判断是否选中
var flag1=0;var checkobj = document.getElementById("CheckBoxList1");var checks = checkobj.getElementsByTagName("input");for(var n=0;n<checks.length;n++){if(checks[n].type=="checkbox" && checks[n].checked==true){flag1=1;}}if(flag1==0){alert("请选择栏目设置!");return false;}
CheckBoxList控件的属性和事件
- AutoPostBack属性:用于设置当单击checkboxList控件时,是否自动回送到服务器。True表示回送;False(默认)表示不回送。
- DataSource属性:用于指定填充列表控件的数据源。
- DataTextField属性:指定DataSource中一个字段,该字段的值对应于列表项的Text属性。
- DataValueField属性:指定DataSource中一个字段,字段的值对应于列表项的Value属性。
- Items属性:表示复选框列表中各个选项的集合,如CheckBoxList1.Items(i)表示第i个选项,i从0开始。每个选项都有以下3个基本属性:
- Text属性:表示每个选项的文本。
- Value属性:表示每个选项的选项值。
- Selected属性:表示该选项是否被选中。
- Count属性:通过Items.Count属性可获得CheckBoxList控件的选项数;
- Add方法:通过items.Add方法可以向CheckBoxList控件添加选项;
- Remove方法:通过items.Remove方法,可从CheckBoxList控件中删除指定的选项;
- Insert方法:通过items.insert方法,可将一个新的选项插入到CheckBoxList控件中;
- Clear方法:通过items.clear方法可以清空CheckBoxList控件中的选项。
- RepeatColumns属性:用于指定在CheckBoxList控件中显示选项占用几列。默认值为0,表示任意多列。
- RepeatDirection属性:用于指定CheckBoxList控件的显示方向。Vertical时,列表项以列优先排列的形式显示;Horizontal时,列项以行优先排列的形式显示。
- RepeatLayout属性:用于设置选项的排列方式。Table(默认)时,以表结构显示,属性值为Flow时,不以表结构显示。
- SelectedIndex属性:用于获取或设置列表中选定项的最低序号索引值。如果列表控件中只有一个选项被选中,则该属性表示当前选定项的索引值。
- SelectedItem属性:用于获取列表控件中索引值最小的选定项。如果列表中只有一个选项被选中,则该属性表示当前选定项。通过该属性可获得选定项的Text和Value属性值。
- SelectedIndexchanged事件:当用户选择了列表中的任意复选框时,都将引发事件。
摘录
for (int i = 0; i < checkedListBox1.Items.Count; i++){if (checkedListBox1.GetItemChecked(i)){MessageBox.Show(checkedListBox1.GetItemText(checkedListBox1.Items[i]));}}
1. 添加项
checkedListBox1.Items.Add("蓝色");checkedListBox1.Items.Add("红色");checkedListBox1.Items.Add("黄色");
2. 判断第i项是否选中,选中为true,否则为false
if(checkedListBox1.GetItemChecked(i)){return true;}else{return false;}
3. 设置第i项是否选中
checkedListBox1.SetItemChecked(i, true); //true改为false为没有选中。
4. 设置全选
添加一个名为select_all的checkbox控件,由其控制checkedListBox是全选还是全不选。
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. 得到全部选中的值,并将选中的项的文本组合成为一个字符串.
string strCollected = string.Empty;for (int i = 0; i < checkedListBox1.Items.Count; i++){if (checkedListBox1.GetItemChecked(i)){if (strCollected == string.Empty){strCollected = checkedListBox1.GetItemText(checkedListBox1.Items[i]);}}else{strCollected = strCollected + "/" + checkedListBox1.GetItemText(checkedListBox1.Items[i]);}}
6. 设置CheckedListBox中第i项的Checked状态
checkedListBox1.SetItemCheckState(i, CheckState.Checked);
7. 全选
private void checkBoxAll_CheckedChanged(object sender, EventArgs e){if (checkBoxAll.Checked){//被选择了则将CheckedListBox中的所有条目都变为Checked状态for (int i = 0; i < checkedListBoxLayerControl.Items.Count;i++){checkedListBoxLayerControl.SetItemCheckState(i,CheckState.Checked);}}else{//否则变成Unchecked状态for (int i = 0;i < checkedListBoxLayerControl.Items.Count; i++){checkedListBoxLayerControl.SetItemCheckState(i, CheckState.Unchecked);}}}
8. checkedListBox 单选设置(代码实现)
private void chkl_ItemAuditing_ItemCheck(object sender,ItemCheckEventArgs e){if (chkl_ItemAuditing.CheckedItems.Count > 0){for (int i = 0; i < chkl_ItemAuditing.Items.Count; i++){if (i != e.Index){this.chkl_ItemAuditing.SetItemCheckState(i,System.Windows.Forms.CheckState.Unchecked);}}}}
9. checkedListBox1显示一个数据库中关键字对应的所有记录
for (int i = 0; i < table.Rows.Count; i++){string name = table.Rows["myname"].ToString();string paw = table.Rows["mypaw"].ToString();checkedListBox1.Items.Add(name + paw);}
10.
for(i=0;i<CheckedListBox.Items.Count;i++){if(CheckedListBox.GetItemText(CheckedListBox.Items)=="你得到的值"){CheckedListBox.SetItemChecked(i,true);}}
11. 清除checkedListBox1中所有的选项
for (int i = 0; i < checkedListBox1.Items.Count; i++){checkedListBox1.Items.Clear();}
12. 设置索引为index的项为选中状态
for (int i = 0; i < checkedListBox1.Items.Count; i++){checkedListBox1.SetItemChecked(i, true);}
13.
for (int i = 0; i < checkedListBox1.Items.Count; i++){if (checkedListBox1.GetSelected(i)){MessageBox.Show(checkedListBox1.CheckedItems.ToString());}}
14. 选中checkedListBox1所有的选项
for(int i = 0; i < checkedListBox1.Items.Count; i++){checkedListBox1.SetItemCheckState(i, CheckState.Checked);}
15.
for (int i = 0; i < checkedListBox1.Items.Count; i++){//如果checkedListBox1的第i项被选中,//则显示checkedListBox1对应的值if (checkedListBox1.GetItemChecked(i)){MessageBox.Show(checkedListBox1.Items.ToString());}}
16. 反向选择checkedListBox1的选项
for (int i = 0; i < checkedListBox1.Items.Count; i++){if (checkedListBox1.GetItemChecked(i)){checkedListBox1.SetItemChecked(i, false);}else{checkedListBox1.SetItemChecked(i, true);}}
17. checkedListBox1中选定的项->checkedListBox2
for (int i = 0; i < checkedListBox1.CheckedItems.Count; i++){checkedListBox2.Items.Add(this.checkedListBox1.CheckedItems);//remove是除去一个具体的值,不是index,注意了this.checkedListBox1.Items.Remove(this.checkedListBox1.CheckedItems);}
18. 绑定数据
checkedListBox1.DataSource = dt;checkedListBox1.DisplayMember = "item";checkedListBox1.ValueMember = "code";//这个属性在checklistbox里是没有的,但是可以直接使用
19.
for (int i = 0; i < checkedListBox1.Items.Count; i++){if (checkedListBox1.GetItemChecked(i)){checkedListBox1.SelectedIndex = i;//利用SelectedValue取得Value值时,只能取得当前焦点项的值。所以要对整个CheckedListBox中的所有勾选项,让其都做一次焦点项才能取得所有勾选的项的值。str+= checkedListBox1.SelectedValue;}}
20.
CheckedlistBox控件比较有用到两个属性分别为:
CheckOnClickTrue:表示单击就选中当前行,为False :要点两下才可以选中。(默认值为False)。ThreeDCheckBoxesTrue:表示三维的选中标记,为False:表示表面的显示标记。(默认值为False)。
问题
但是,在得到value值时出现了有点问题。 由于我是在selectedindexchanges时触发读取value事件,导致在循环焦点项时发生无限循环的异常。 于是用了比较传统的手法来解决这个问题。 将所要得到的字符串定义成全局变量,在高亮处时判断是否被选中,选中则加上该value值,没有选中则替换掉该value值。
/** 先修改checkonclick属性值,使得控件在单击时选中*/string s = string.Empty;private void clbParameter_SelectedIndexChanged(object sender, EventArgs e){// checkList.Clear();QuotaModel Quota = new QuotaModel();string ParameterText = "";//value值string ParameterRowCol = "";//参数值//string name=this.clbParameter.SelectedItem.ToString();string name = this.clbParameter.Text;//当前checklistbox高亮文本值string ParameterValue = string.Empty;ParameterValue = this.clbParameter.SelectedValue.ToString();//当前checklistbox高亮value值if (QuotaListCheck != null){foreach (QuotaModel model in QuotaListCheck){//获取行与列值if (model.Quota_Id == ParameterValue){Quota.Formext_Row = model.Formext_Row;Quota.Formext_Col = model.Formext_Col;ParameterRowCol = "${" + Quota.Formext_Col + Quota.Formext_Row + "}";}}}//选项状态改变时遍历判断是否被选中for (int i = 0; i < clbParameter.Items.Count; i++){string ItemName = string.Empty;ItemName = this.clbParameter.GetItemText(this.clbParameter.Items[i]);if (clbParameter.GetItemChecked(i)){if (ParameterText != ""){ParameterText = ParameterText + "+";}ParameterText += ItemName;if (name.Equals(ItemName)){if (s != ""){s += "+";}s += ParameterRowCol;}}else{if (name.Equals(ItemName)){int index = s.IndexOf(ParameterRowCol);//if (s.Contains("+"))if (index == 0) //判断读取到的value值是否是在字符串的第一位{ //若是第一位,判断后续是否还有其他字符if (s.Contains("+")) //若有其他字符,连同后面的“+”号一块替换{ParameterRowCol += "+";}}else{ //如果不是在第一位,则删除该字符与之前的“+”号ParameterRowCol = "+" + ParameterRowCol;}if (ParameterRowCol != ""){s = s.Replace(ParameterRowCol, "");}}}}this.txtCheckValue.Text = ParameterText;this.txtCheckParameter.Text = s;}
