C# CheckBox與RadioButton

一般RadioBox稱爲單選按鈕,CheckBox稱爲多選按鈕,這兩個控件都是從ButtonBase類中派生,能夠將其視爲按鈕。數組

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

RadioButton和CheckBox控件都有一個Checked屬性,若是控件處於選擇狀態,則Checked屬性的值爲true不然爲false。當選擇狀態發生改變後會引起CheckedChanged事件,能夠經過這個事件開實時得知控件的選擇狀態。3d

一、創建這樣的一個窗口 ,使用了CheckBox和RadioBox控件code

二、添加兩個label控件(用做信息輸出)orm

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

四、在OncheckChanged添加以下代碼blog

  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);
            }
        }

五、在RadioButton添加點擊共享事件事件

 

六、在共享事件中輸入代碼字符串

  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 = "";
        }

七、運行效果string

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

相關文章
相關標籤/搜索