简体   繁体   English

如何在C#中从Form1启动Form2?

[英]How to launch form2 from form1 in C#?

OK, I am about 1 week into programming in C# ever... I am writing a GUI application that has two forms. 好的,我大约用C#进行编程大约需要1周的时间。我正在编写一种具有两种形式的GUI应用程序。 Form1 is the main form, and have quite a bit of codes that are working nicely. Form1是主要形式,并且有很多代码可以很好地工作。 Form2 is supposed to be launched, when Form1 is handling exception.. 当Form1处理异常时,应该启动Form2

Form1 and Form2 are both created in VS Solution Explorer, so they are not code created on the fly. Form1Form2都是在VS Solution Explorer中创建的,因此它们不是动态创建的代码。

In Form1.cs ... 在Form1.cs中...

namespace Launcher
{
    public partial class Form1: Form  
    {  
        // ...  
        private void button2_Click(object sender, EventArgs e)
        {
            try  
            {  
                //some codes  
            }  
            catch (SomeException)  
            {  
                Form Form2 = new Form();  
                Form2.Show();  
            }
        }
    }
}

In addition .. in Program.cs .. 另外..在Program.cs中..

using System.Windows.Forms;  

namespace LauncherCSharp  
{
    static class Program  
    {
    /// <summary>  
    /// The main entry point for the application.  
    /// </summary>  

        static void Main()  
        {  
            Application.EnableVisualStyles();  
            Application.SetCompatibleTextRenderingDefault(false);  
            Application.Run(new Form1());  
        }
    }
}

Problem is .. Form2.Show() will pop up a brand new Form2 , and not the one I've defined in Solution Explorer. 问题是.. Form2.Show()将弹出一个全新的Form2 ,而不是我在解决方案资源管理器中定义的那个。 I think this is related to the new Form() line above, but if I don't have this new Form() line, the compiler complained about Form2.Show() ..Cannot access non-static method "show" in static context. 我认为这与上面的新Form()行有关,但是如果我没有新Form()行,则编译器会抱怨Form2.Show() ..无法在静态中访问非静态方法“ show”上下文。

Any ideas? 有任何想法吗?

You aren't actually creating Form2 您实际上不是在创建Form2

Your code 您的密码

Form Form2 = new Form();

Should probably be 应该是

Form2 form2 = new Form2();

or replace Form2 with the actual name of your form2. 或将Form2替换为您的Form2的实际名称。

In C#, we create an instances of an object (in your case the object is the form) by the following syntax 在C#中,我们通过以下语法创建对象的实例(在您的情况下,该对象是表单)

ObjectName yourVariableName = new ObjectName();

We can then refer to this object by using the "yourVariableName". 然后,我们可以使用“ yourVariableName”来引用该对象。 eg 例如

yourVariableName.Show(); // Show the form

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM