天天看點

winform 複選框控件指派的小技巧

本人在開發Winform程式中,也有一個類似的小技巧,不是清空控件值,而是指派,給複選框指派和擷取值的小技巧,分享讨論一下。

應用場景是這樣的,如果你有一些需要使用複選框來呈現内容的時候,如下面兩圖所示:

以上的切除部分的内容,是采用在GroupBox中放置多個CheckBox的方式;其實這個部分也可以使用Winform控件種的CheckedListBox控件來呈現内容。如下所示。

不管采用那種控件,我們都會涉及到為它指派的麻煩,我這裡封裝了一個函數,可以很簡單的給控件 指派,大緻代碼如下。

CheckBoxListUtil.SetCheck(this.groupRemove, info.切除程度);

那麼取控件的内容代碼是如何的呢,代碼如下:

info.切除程度 = CheckBoxListUtil.GetCheckedItems(this.groupRemove);

指派和取值通過封裝函數調用,都非常簡單,也可以重複利用,封裝方法函數如下所示。

    public class CheckBoxListUtil

    {

        /// <summary>

        /// 如果值清單中有的,根據内容勾選GroupBox裡面的成員.

        /// </summary>

        /// <param name="group">包含CheckBox控件組的GroupBox控件</param>

        /// <param name="valueList">逗号分隔的值清單</param>

        public static void SetCheck(GroupBox group, string valueList)

        {

            string[] strtemp = valueList.Split(',');

            foreach (string str in strtemp)

            {

                foreach (Control control in group.Controls)

                {

                    CheckBox chk = control as CheckBox;

                    if (chk != null && chk.Text == str)

                    {

                        chk.Checked = true;

                    }

                }

            }

        }

        /// 擷取GroupBox控件成員勾選的值

        /// <returns>傳回逗号分隔的值清單</returns>

        public static string GetCheckedItems(GroupBox group)

            string resultList = "";

            foreach (Control control in group.Controls)

                CheckBox chk = control as CheckBox;

                if (chk != null && chk.Checked)

                    resultList += string.Format("{0},", chk.Text);

            return resultList.Trim(',');

        /// 如果值清單中有的,根據内容勾選CheckedListBox的成員.

        /// <param name="cblItems">CheckedListBox控件</param>

        public static void SetCheck(CheckedListBox cblItems, string valueList)

                for (int i = 0; i < cblItems.Items.Count; i++)

                    if (cblItems.GetItemText(cblItems.Items[i]) == str)

                        cblItems.SetItemChecked(i, true);

        /// 擷取CheckedListBox控件成員勾選的值

        public static string GetCheckedItems(CheckedListBox cblItems)

            for (int i = 0; i < cblItems.CheckedItems.Count; i++)

                if (cblItems.GetItemChecked(i))

                    resultList += string.Format("{0},", cblItems.GetItemText(cblItems.Items[i]));

    }

以上代碼分為兩部分, 其一是對GroupBox的控件組進行操作,第二是對CheckedListBox控件進行操作。

這樣在做複選框的時候,就比較友善一點,如我采用第一種GroupBox控件組方式,根據内容勾選的界面如下所示。

應用上面的輔助類函數,如果你是采用GroupBox方案,你就可以随便拖幾個CheckBox控件進去就可以了,也犯不着給他取個有意義的名字,因為不管它是張三還是李四,隻要它的父親是GroupBox就沒有問題了。