标准的CheckBoxList控件只能获取最后一个选择项,不少时候处理起来很麻烦,每次都要本身写代码获取选中项的值,今天写了一个控件,继承了CheckBoxList,添加了几个属性:SelectedValues、SelectedTexts、SelectedItems。
- /// <summary>
- /// MyCheckBoxList,获取多个选择项
- /// </summary>
- [ToolboxData("<{0}:MyCheckBoxList runat=server></{0}:MyCheckBoxList>")]
- public class MyCheckBoxList : CheckBoxList
- {
- /// <summary>
- /// 获取或设置选中项的值,以半角逗号分隔
- /// </summary>
- [Browsable(true)]
- [Bindable(true)]
- [Description("获取或设置选中项的值,以半角逗号分隔")]
- public string SelectedValues
- {
- get
- {
- string ValueStr = string.Empty;
- for (int k = 0; k <= this.Items.Count - 1; k++)
- {
- if (this.Items[k].Selected)
- {
- ValueStr += this.Items[k].Value + ",";
- }
- }
- if (ValueStr != string.Empty)
- {
- ValueStr = ValueStr.Substring(0, ValueStr.Length - 1);
- }
-
- return ValueStr;
- }
-
- set
- {
- if (value != string.Empty)
- {
- string[] values = value.Split(',');
-
- for (int k = 0; k <= this.Items.Count - 1; k++)
- {
- for (int j = 0; j <= values.Length - 1; j++)
- {
- if (values[j] == this.Items[k].Value)
- {
- this.Items[k].Selected = true;
- }
- }
- }
- }
- }
- }
-
- /// <summary>
- /// 获取或设置选中项的文本,以半角逗号分隔
- /// </summary>
- [Browsable(true)]
- [Bindable(true)]
- [Description("获取或设置选中项的文本,以半角逗号分隔")]
- public string SelectedTexts
- {
- get
- {
- string TextStr = string.Empty;
- for (int k = 0; k <= this.Items.Count - 1; k++)
- {
- if (this.Items[k].Selected)
- {
- TextStr += this.Items[k].Text + ",";
- }
- }
- if (TextStr != string.Empty)
- {
- TextStr = TextStr.Substring(0, TextStr.Length - 1);
- }
-
- return TextStr;
- }
-
- set
- {
- if (value != string.Empty)
- {
- string[] values = value.Split(',');
-
- for (int k = 0; k <= this.Items.Count - 1; k++)
- {
- for (int j = 0; j <= values.Length - 1; j++)
- {
- if (values[j] == this.Items[k].Text)
- {
- this.Items[k].Selected = true;
- }
- }
- }
- }
- }
- }
-
- /// <summary>
- /// 获取或设置选中项,返回ListItemCollection
- /// </summary>
- [Browsable(true)]
- [Bindable(true)]
- [Description("获取或设置选中项,返回ListItemCollection")]
- public ListItemCollection SelectedItems
- {
- get
- {
- ListItemCollection Items = new ListItemCollection();
- for (int k = 0; k <= this.Items.Count - 1; k++)
- {
- if (this.Items[k].Selected)
- {
- Items.Add(this.Items[k]);
- }
- }
-
- return Items;
- }
-
- set
- {
- ListItemCollection Items = (ListItemCollection)value;
-
- for (int k = 0; k <= this.Items.Count - 1; k++)
- {
- for (int i = 0; i <= Items.Count - 1;i++ )
- {
- if (this.Items[k].Equals(Items[i]))
- {
- this.Items[k].Selected = true;
- }
- }
- }
- }
- }
- }