c#中怎么获取另一个窗体的checkbox状态?
private void button1_Click(object sender, EventArgs e)
{
Form2 frm = new Form2();
MessageBox.Show(frm.checkBox1.CheckState.ToString());
} 展开
专门来帮你写一个:
From1里面的:
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
List<CheckBox> list = new List<CheckBox>();
private void Form1_Load(object sender, EventArgs e)
{
foreach(Control cb in this.Controls)
{
if (cb is CheckBox)
{
list.Add(cb as CheckBox);
}
}
}
private void button1_Click(object sender, EventArgs e)
{
Form2 frm2 = new Form2(list);
frm2.Show();
}
}
}
From2里面的:
namespace WindowsFormsApplication1
{
public partial class Form2 : Form
{
public Form2(List<CheckBox> lcb)
{
listCheckBox = lcb;
InitializeComponent();
}
List<CheckBox> listCheckBox = null;
private void Form2_Load(object sender, EventArgs e)
{
foreach (CheckBox cb in listCheckBox)
{
//Unchecked 就是没被选中 和false一个意思
this.textBox1.Text += cb.Name + ":" + cb.Checked + ";" + cb.CheckState + "\r\n";
}
}
}
}
你可以不停的点击Form1里面的button1看Form2的textBox1里面值的变化
这样才能在Form1里访问Form2
并且代码需要添加一句话
private void button1_Click(object sender, EventArgs e)
{
Form2 frm = new Form2();
frm.Owner = this;//添加这句话很重要,Form.Owner 属性获取或设置拥有此窗体的窗体
MessageBox.Show(frm.checkBox1.CheckState.ToString());
}
与当前的 form2 不一样吧
把当前 form2 的变量传进去才行
可以取出一个false