天天看點

C# CheckBox與RadioButton

通常RadioBox稱為單選按鈕,CheckBox稱為多選按鈕,這兩個控件都是從ButtonBase類中派生,可以将其視為按鈕。

  多個checkBox之間的選擇是互相獨立的,互補影響。多個RadioButton之間是互斥的,隻能選擇其中一個。同一個容器下的多個RadioButton之間互斥,來自不同容器的RadioButton 對象是相對獨立的。

RadioButton和CheckBox控件都有一個Checked屬性,如果控件處于選擇狀态,則Checked屬性的值為true否則為false。當選擇狀态發生改變後會引發CheckedChanged事件,可以通過這個事件開實時得知控件的選擇狀态。

1、建立這樣的一個視窗 ,使用了CheckBox和RadioBox控件

C# CheckBox與RadioButton

2、添加兩個label控件(用作資訊輸出)

C# CheckBox與RadioButton

3、添加一個CheckBox共享處理事件 CheckedChanged當發生改變的時候出發該事件

C# CheckBox與RadioButton

4、在OncheckChanged添加如下代碼

private void OnCheckChanged(object sender, EventArgs e)
        {
            DisplayCheckResults();//調用自定義方法
        }
        private void DisplayCheckResults()
        {
            if (label1 != null)
            {
                //建立一個List<string>執行個體
                List<string> strList = new List<string>();
                //将被選中的CheckBox的Text屬性的内容添加到清單中
                if (checkBox1.Checked)
                    strList.Add(checkBox1.Text);
                if (checkBox2.Checked)
                    strList.Add(checkBox2.Text);
                if (checkBox3.Checked)
                    strList.Add(checkBox3.Text );
                
                //字元拼接   串聯字元串數組的所有元素,其中在每個元素之間使用指定的分隔符。
                // public static String Join(String separator, params String[] value);
                string res = string.Join("、", strList.ToArray());
                //判斷是否全部都沒有被選擇,如果全部都沒有被選擇清除label1.text
                if((checkBox1.Checked  == false) && (checkBox2.Checked  == false)  && (checkBox3.Checked  == false ))
                    label1.Text = "";
                else 
                // 将指定字元串中的一個或多個格式項替換為指定對象的字元串表示形式。
                label1.Text = string.Format("選擇了:{0}",res);
            }
        }      

5、在RadioButton添加點選共享事件

C# CheckBox與RadioButton

6、在共享事件中輸入代碼

private void OnClick(object sender, EventArgs e)
        {
            if(radioButton1 .Checked )
            label2.Text = string.Format("{0}", radioButton1.Text);
            else if(radioButton2.Checked )
            label2.Text = string.Format("{0}", radioButton2.Text);
           else  if (radioButton3.Checked)
                label2.Text = string.Format("{0}", radioButton3.Text);
            else label2.Text = "";
        }      

7、運作效果

C# CheckBox與RadioButton

勾選對應的框彈出對應的字元。

轉載于:https://www.cnblogs.com/hjxzjp/p/7688072.html