单击按钮时显示新表单

sar*_*own 6 c# winforms

我是C#的新手。我试图在form1中单击按钮时显示一个新的窗体(form2)。

这是我的代码。

        using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

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

        private void Form1_Load(object sender, EventArgs e)
        {

        }
        private void button5_Click(object sender, EventArgs e)
        {   
            Form2 form2 = new Form2();
            form2.ShowDialog();            
         }
    }
}
Run Code Online (Sandbox Code Playgroud)

错误显示

找不到类型或名称空间名称“ Form2”(是否缺少using指令或程序集引用?)

这是我的form2代码。

    using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

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

        private void Form2_Load(object sender, EventArgs e)
        {

        }
    }
}
Run Code Online (Sandbox Code Playgroud)

对于form2,我只是制作设计界面。

我所知道的使用Java时,我只需要先声明该对象。我该怎么办?

Ume*_*esh 5

我看不出有任何理由让你的代码失败,除非你有任何错字。我已经尝试了与您相同的代码,并且在我的机器上运行良好。

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Windows.Forms;

    namespace winapp
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
            }
            private void button1_Click(object sender, EventArgs e)
            {
                Form2 frm2 = new Form2();
                frm2.ShowDialog();
            }
        }




    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Windows.Forms;

    namespace winapp
    {
        public partial class Form2 : Form
        {
            public Form2()
            {
                InitializeComponent();
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)


com*_*ech 1

在 form1 中,您正在使用 Form2 的构造函数:

public partial class Form1 : Form
{
    public Form2()
    {
        InitializeComponent();
    }
Run Code Online (Sandbox Code Playgroud)

如果你把它改成

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }
Run Code Online (Sandbox Code Playgroud)

你应该没事的。