选中form2上的复选框时如何更改Form1 label.text? [英] How to make Form1 label.text change when checkbox on form2 is checked?

查看:18
本文介绍了选中form2上的复选框时如何更改Form1 label.text?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对 c# 非常陌生,正在尝试使用 2 种不同形式的第一次实验.

I'm very new to c# and am trying my first experiments with 2 different forms.

我想让你在 Form1 上有一个 label1 和一个 button1,在 Form2 上有一个 checkbox1.

I'd like to make it so you have a label1 and a button1 on Form1, and a checkbox1 on Form2.

Form1 上的 button1 将打开 Form2,一旦您选中 Form2 上的 checkbox1,label1 中的文本就会发生变化.

the button1 on Form1 opens Form2, and once you check checkbox1 on Form2, the text in label1 changes.

我认为这必须使用事件来完成,但到目前为止,事件是唯一真正让我感到困惑的事情,所以我想本质上这个问题更多地是关于事件的使用.如果我在 MSDN 和其他网站上查找,我也会发现它非常混乱.

I'm thinking this has to be done using events, but events are the only thing up to now that genuinely confuse me, so I guess in essence this question is more about the usage of events. Which I also find terribly confusing if I look it up on MSDN and other websites.

非常感谢您的帮助,这让我感到非常愚蠢.

Help would be very much appreciated, this is making me feel extremely stupid.

推荐答案

您可以直接从 Form1 实例订阅 Form2 实例中复选框的 CheckedChanged 事件.在 Form1 内部,就在显示 Form2 之前订阅复选框的 CheckedChanged 事件

You can subscribe to the event CheckedChanged of the checkbox in the Form2 instance, directly from the Form1 instance. Inside Form1, just before displaying the Form2 subscribe to the CheckedChanged event of the checkbox

Form2 frm = new Form2();
frm.chkBox1.CheckedChanged += new EventHandler(this.ReceiveCheckedChanged);
frm2.ShowDialog();

然后在 Form1 (this) 中定义 Form2 中引发的 checkedChanged 事件的处理程序

and then define in Form1 (this) the handler for the checkedChanged event raised in Form2

private void ReceiveCheckedChanged(object sender, EventArgs e)
{
   CheckBox chk = sender as CheckBox;
   if(chk.Checked)
       this.label1.Text = "Checked";
   else
       this.label1.Text = "UnChecked";
}

为此,您需要将复选框上的 Modifiers 属性从 Private 更改为 Public

for this to work you need to change the property Modifiers on the checkbox from Private to Public

通过这种方式,您的 Form2 不需要知道有一个 Form1,并且每次有人单击复选框时,您都需要更改另一个表单中的标签.更改其内部状态(标签上的文本)的责任在于已将其要求通知系统的 Form1.

In this way your Form2 doesn't need to know that there is a Form1 and that every time someone clicks on the checkbox you need to change a label in another form. The responsability to change its internal state (the text on the label) is on Form1 who has notified the system of its requirements.

这篇关于选中form2上的复选框时如何更改Form1 label.text?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆