C# CheckBox與RadioButton

來源:互聯網
上載者:User

標籤:字串表   list   派生   rgs   oid   div   選項按鈕   checkbox   對象   

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

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

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

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

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

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

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添加點擊共用事件

 

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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.