zoukankan      html  css  js  c++  java
  • C# CheckBox与RadioButton

    通常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、运行效果

    勾选对应的框弹出对应的字符。

  • 相关阅读:
    关于win10输入法问题(打不出中文)解决方法
    Docker 修改默认存储位置
    Enabling and Mounting NFS on CoreOS
    docker run mysql
    Specified key was too long; max key length is 767 bytes mysql
    C# 实现 Snowflake算法 ID生成
    无忧之道:Docker中容器的备份、恢复和迁移
    IIS Express 虚拟目录
    从零開始学android&lt;AnalogClock与DigitalClock时钟组件.三十一.&gt;
    jquery版本号升级不兼容的问题:$(&quot;input&quot;).attr(&quot;value&quot;)功能发生改变
  • 原文地址:https://www.cnblogs.com/hjxzjp/p/7688072.html
Copyright © 2011-2022 走看看