且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

从一个页面C#windows窗体应用程序重定向到另一个页面

更新时间:2023-01-08 13:24:55

每次在Method中创建一个新Form时,该Form的生命周期是仅限于方法的范围。因此,您在这里显示的两个方法中创建的新表单在这些方法之外基本上不存在。



假设您有一个主表单(您正在使用Visual Studio创建的默认Windows窗体应用程序:



1.在主窗体的类范围内创建其他两个窗体的可重用实例:
Every time you create a new Form inside a Method, the "life-time" of that Form is limited to the scope of the Method. So, the new Forms you create inside the two Methods you show here essentially "don't exist" outside those Methods.

Assuming you have a "Main Form" (that you are using the default Windows Form App that Visual Studio creates):

1. create re-usable instances of your other two Forms in the Main Form's Class scope:
Form2 form2Instance = new Form2();

Form3 form3Instance = new Form3();

并根据需要显示(使用显示)。 />


如果您希望在这些次要表单上使用按钮将您带回主表单怎么办?在辅助表单中公开公共操作委托:

and make visible (using 'Show) as necessary.

What if you want to have a Button on these "secondary" Forms that takes you back to the Main Form ? Expose a Public Action delegate in the secondary Forms:

// in Forms 2 and 3

public Action<form> GetBackHome { set; get; }</form>

然后,当用户单击表单2中的按钮或3名为'GoBackToMain:

Then, when the user clicks a Button in Forms 2, or 3 named 'GoBackToMain:

private void GoBackToMain_Click(object sender, EventArgs e)
{
     if(GetBackHom != null) GetBackHome(this);
}

然后,在主窗体中,您可以将return from委托实例插入到Forms 2和3中:

Then, in the Main Form, you can insert a "return from" delegate instance into Forms 2, and 3:

form2Instance.GetBackHome += returnedFromSecondaryForms;

private void ReturnedFromSecondaryForms(Form theForm)
{
    Console.WriteLine("returned from Form: {0}", theForm.Name);

    // return Focus to the Main Form
    this.Focus();

   // do whatever you want to with the Form you returned from
   // Hide it ?
   theForm.Hide();
}

注意:



1.仔细考虑何时想要'隐藏表单,而不是'关闭它。使用Hide();当你想让表格活着时,重新使用它。使用关闭();当你想删除对Form的引用时(除非你做了一些奇怪的事情,否则引用将自动被垃圾收集)。

Note:

1. think carefully about when you want to 'Hide a Form, rather than 'Close it. Use Hide(); when you want to keep the Form "alive," re-use it. Use "Close(); when you want to delete the reference to the Form (the reference will then be garbage-collected automatically unless you've done something weird).


首先, 页面用于WebForms。但是,如果您的意思是表单,请访问以下链接。



***.com :如何在表单之间导航
First of all, "Page" is used for WebForms. However, if you mean "Form", pay visit to the the link below.

***.com: How can I navigate between forms