標準的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;
- }
- }
- }
- }
- }
- }