Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
670 views
in Technique[技术] by (71.8m points)

c# - Passing Data Between Forms

I have 3 winforms in my project and on Form3 there is a checkbox. What I want to be able to do is to click this checkbox, then when the form is exited make the same check (whether checked or not) on the one in Form1. The existing code I have is follows, but it just won't work, am I missing a trick somewhere? Thanks.

//Form3

Form1 setDateBox = new Form1();
setDateBox.setNoDate(checkBox1.Checked);

//Form1

public void setNoDate(bool isChecked)
{
    checkBox1.Checked = isChecked;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

A couple of approaches:

1 - Store the Form1 variable "setDateBox" as a class member of Form3 and then access the "setNoDate" method from the checkboxes CheckedChanged event handler:

private void checkBox1_CheckedChanged(object sender, EventArgs e)
{
    setDateBox.setNoDate(checkBox1.Checked);
}

2 - If you do not wish to store setDateBox as a class member or you need to update more than one form, you could Define an event within Form3 which like so:

public event EventHandler<CheckedChangedEventArgs> CheckBox1CheckedChanged;

...

public class CheckedChangedEventArgs : EventArgs
{
    public bool CheckedState { get; set; }

    public CheckedChangedEventArgs(bool state)
    {
        CheckedState = state;
    }
}

Create a handler for the event in Form1:

public void Form1_CheckBox1CheckedChanged(object sender, CheckedChangedEventArgs e)
{
    //Do something with the CheckedState
    MessageBox.Show(e.CheckedState.ToString());
}

Assign the event handler after creating the form:

Form1 setDateBox = new Form1();
CheckBox1CheckedChanged += new EventHandler<CheckedChangedEventArgs>(setDateBox.Form1_CheckBox1CheckedChanged);

And then fire the event from Form3 (upon the checkbox's checked state changing):

private void checkBox1_CheckedChanged(object sender, EventArgs e)
{
    if(CheckBox1CheckedChanged != null)
        CheckBox1CheckedChanged(this, new CheckedChangedEventArgs(checkBox1.Checked));
}

Hope this helps.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...