在c#中以另一种形式在复选框之间传递值
本文关键字:之间 复选框 另一种 | 更新日期: 2023-09-27 18:01:54
我需要你的帮助。我有两个表格,表格1和表格2。在Form1中,我有一个checkBox1,在Form2中,我有一个checkBox2。我想要的只是checkBox1的值在checkBox2中自动传递。
Thanks in advance
首先,在多表单应用程序中,不应该允许表单与表单直接接触。然而,我可以想到一个方法,我在这里提出考虑到你是一个特殊的情况。因此,该方法可能违反通常的最佳实践。
方法
-
将表单中的复选框设置为Public。您可以通过在设计模式中单击复选框,然后在属性窗口的Modifiers下选择Public来实现。这一步使你的复选框可以从表单的外部实例访问。
-
在Form1中CheckBox的
CheckedChanged
事件中编写以下代码((Form2)(Application.openForms["Form2"])).checkBox1.Checked = this.checkBox1.Checked;
但是,我强烈建议您根据应用程序的需要重新审视您的策略。
On Form1:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void checkBox1_CheckedChanged(object sender, EventArgs e)
{
Form2 a = new Form2();
a.c = checkBox1.Checked;
a.ShowDialog();
}
}
在Form2 :
public partial class Form2 : Form
{
public bool c;
public Form2()
{
InitializeComponent();
}
private void Form2_Load(object sender, EventArgs e)
{
checkBox1.Checked = c;
}
}
MDI父类中的所有Form2实例都将反映对窗体上放置的CustomCheckBox控件Checked属性的任何更改。当然,当将CustomCheckBox放置在任何MDI子窗体上时,只需设置适当的事件,如Form2。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication1 {
public partial class Form2 : Form {
public Form2() {
InitializeComponent();
CustomCheckBox.CheckChanged += (object sender, EventArgs e) => {
if (sender != m_customCheckBox) { m_customCheckBox.Checked = CustomCheckBox.GetCheck(); }
};
FormClosed += (object _sender, FormClosedEventArgs _e) => {
CustomCheckBox.CheckChanged -= (object __sender, EventArgs __e) => { };
};
}
};
};
////////////////////////////////////////////////
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication1 {
public class CustomCheckBox : CheckBox {
static private bool? m_checked = null;
static private object m_synchRoot = new object();
static public event EventHandler CheckChanged;
public CustomCheckBox() {
if (HasCheckValue) {
// Do this BEFORE we set up the CheckChanged event so that
// we do not needlessly kick off the CustomCheckBox.CheckChanged
// event for any other existing CustomCheckBoxes (as they already
// have their Checked property properly set)...
Checked = CustomCheckBox.GetCheck();
}
this.CheckedChanged += new EventHandler(OnCheckedChanged);
}
protected void OnCheckedChanged(object sender, EventArgs e) {
if (CustomCheckBox.HasCheckValue && this.Checked == CustomCheckBox.GetCheck()) {
return;
} else {
CustomCheckBox.SetCheck(this.Checked);
if (CustomCheckBox.CheckChanged != null) {
CustomCheckBox.CheckChanged(sender, e);
}
}
}
static public bool HasCheckValue {
get {
lock (m_synchRoot) {
return m_checked.HasValue;
}
}
}
static public bool GetCheck() {
lock (m_synchRoot) {
return m_checked.Value;
}
}
static private void SetCheck(bool _check) {
lock (m_synchRoot) {
m_checked = _check;
}
}
};
};