简体   繁体   English

选中复选框后如何执行代码? C#

[英]How to execute code the second a checkbox is checked? C#

When I usually work with checkboxes, I check to see if the box is checked with the code below: 当我通常使用复选框时,我会检查该复选框是否被以下代码选中:

if (checkBox1.Checked)
{    
     Label1.BackColor = Color.Red;
}

This code is usually attached to a button that sets into motion when it's clicked by the user. 这段代码通常附加在一个按钮上,当用户单击该按钮时,该按钮将启动。 This time, however, I want to do something, like change the color of a label, the very SECOND the checkbox is checked by the user. 但是,这一次,我想做一些事情,例如更改标签的颜色,第二个复选框就是由用户选中的。 That is, I don't want to wait until the user pushes some other button to check if the checkbox is checked in order for the label's color to change. 也就是说,我不想等到用户按下其他按钮来检查是否已选中复选框以更改标签的颜色。

How do I do this? 我该怎么做呢?

Sounds like you need a CheckedChanged event handler . 听起来您需要一个CheckedChanged事件处理程序 That one's for ASP.Net, but there's a version for winforms as well (and xaml, and so on.) 那是针对ASP.Net的,但是还有一个针对winforms的版本 (以及xaml等)。

Then you have to write code inside CheckedChanged Event of checkBox as below: 然后,您必须在checkBox的CheckedChanged事件内编写代码,如下所示:

private void checkBox1_CheckedChanged(object sender, EventArgs e)
            {
                if (checkBox1.Checked)
                    label1.ForeColor = Color.Red;
            }

您为什么不参加CheckChanged事件并在那里实现您的想法?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM