【问题标题】:How to cancel RadioButton or CheckBox checked change如何取消 RadioButton 或 CheckBox 选中的更改
【发布时间】:2010-11-25 04:42:34
【问题描述】:

有什么方法可以在 RadioButton 或 CheckBox 改变之前取消它的状态改变?

我希望有一个简单的事件,例如 CheckedChanging 或 BeforeCheckedChange。

我真的想避免监听鼠标点击和按键。但如果您知道使用鼠标点击和按键的可靠方法,请解释一下。

我正在使用带有标准 Winforms 控件的 .NET 2.0。

【问题讨论】:

    标签: .net winforms events


    【解决方案1】:

    将自动检查设置为 false。

    覆盖 OnClick 以手动选中复选框

    【讨论】:

    • 我什至不知道 AutoCheck 存在。这正是我想要的,谢谢。
    • 我想知道为什么这与其他一些控件不同,在这些控件中,如果您想取消 @ 的更改,您可以在其中设置 e.Cancel = true; 987654323@财产。
    • 在单选按钮的情况下,有来自文档的重要说明:If the AutoCheck property is set to false, a group of RadioButton controls will not act as a mutually exclusive group and the Checked property must be updated in code
    【解决方案2】:

    代码演示的AutoCheck,给Click事件增加了确认提示。

    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            this.checkBox1.AutoCheck = false;
            this.checkBox1.Click += new System.EventHandler(this.checkBox1_Click);
        }
    
        private void checkBox1_Click(object sender, EventArgs e)
        {
            CheckBox checkBox = (CheckBox)sender;
            if (!checkBox.Checked)
            {
                DialogResult dialogResult = MessageBox.Show(
                    "Are you sure?", "my caption",
                     MessageBoxButtons.YesNo);
    
                if (dialogResult == DialogResult.Yes)
                {
                    checkBox.Checked = true;
                }
            }
            else
            {
                checkBox.Checked = false;
            }
        }
    }
    

    【讨论】:

    • 在控件获得焦点时按下空格键是否有效?
    • 如果我是提出这个问题的人,我一定会接受这个答案
    【解决方案3】:

    我用它来取消单选按钮检查。

     private void radioButton1_MouseClick(object sender, MouseEventArgs e)
        {
            RadioButton r = (RadioButton)sender;
            r.Checked = !(r.Checked);
        }
    

    【讨论】:

    • 我使用这种方法的唯一问题是之前的单选按钮已经被取消选中,所以这并不能完全撤消点击。为此,我必须为每个单选按钮的 CheckedChanged 事件添加一个事件处理程序,当未选中单选按钮时,保存未选中的按钮,以防我需要再次检查以完全撤消单击。
    【解决方案4】:
    private void cbSuspended_CheckedChanged(object sender, EventArgs e)
    {
        var result = MessageBox.Show("Are you sure?", "Change status", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);
        if (result != DialogResult.Yes)
        {
            cbSuspended.CheckedChanged -= cbSuspended_CheckedChanged;
            cbSuspended.Checked = !cbRemoved.Checked;
            cbSuspended.CheckedChanged += cbSuspended_CheckedChanged;
            return;
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-08-19
      • 1970-01-01
      • 2016-01-21
      • 2021-09-25
      • 1970-01-01
      • 2013-03-18
      • 1970-01-01
      相关资源
      最近更新 更多