Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

go back to the previous form (c#)

I know how to go to another form in modal mode just like what I did below:

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    Form2 myNewForm = new Form2();
    private void button1_Click(object sender, EventArgs e)
    {
        this.Hide();
        myNewForm.ShowDialog();


    }
}

This is my second form, how do I go back to the previous form?

public partial class Form2 : Form
{
    public Form2()
    {
        InitializeComponent();
    }

    private void Form2_Load(object sender, EventArgs e)
    {

    }
    private void button1_Click(object sender, EventArgs e)
    {
        this.Hide();
        // what should i put here to show form1 again
    }

}
See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

When you call ShowDialog on a form, it runs until the form is closed, the form's DialogResult property is set to something other than None, or a child button with a DialogResult property other than None is clicked. So you could do something like

public partial class Form1
{
    ...
    private void button1_Click(object sender, EventArgs e)
    {
        this.Hide();
        newform.ShowDialog();
        // We get here when newform's DialogResult gets set
        this.Show();
    }
}

public partial class Form2
{
    ...
    private void button1_Click(object sender, EventArgs e)
    {
        // This hides the form, and causes ShowDialog() to return in your Form1
        this.DialogResult = DialogResult.OK;
    }
}

Although if you're not doing anything but returning from the form when you click the button, you could just set the DialogResult property on Form2.button1 in the form designer, and you wouldn't need an event handler in Form2 at all.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...