如何使用按钮名称在C#中打开新表单?

时间:2016-05-23 17:11:25

标签: c# winforms

我正在制作一个小应用程序,我不知道如何使用点击按钮的参数打开应用程序的新窗口。 例如:如果我点击氢气,我想打开一个名为prvek的表格,它将显示有关它的信息。

抱歉我的英语不好。这是主窗口的截图: Main window

2 个答案:

答案 0 :(得分:1)

在Windows窗体中打开表单只需要创建该表单的实例并在该实例上调用.Show()。例如:

var someForm = new SomeForm();
someForm.Show();

如果要将值传递给该表单,可以将它们设置为构造函数参数。例如,在SomeForm

public SomeForm(int someValue)
{
    // do something with someValue
}

然后当你创建它时:

var someForm = new SomeForm(aValue);
someForm.Show();

或者,如果这些值不是必需的,但您恰好在此时可以使用它们,可以将它们设置为属性。在SomeForm

public int SomeValue { get; set; }

然后当你创建它时:

var someForm = new SomeForm();
someForm.SomeValue = aValue;
someForm.Show();

或:

var someForm = new SomeForm { SomeValue = aValue };
someForm.Show();

当然,您获得自己的价值取决于您自己。我不确定你点击按钮的参数是什么意思"。但是在click事件中应该有一个object sender,它是对触发事件的UI元素的引用。

因此,例如,如果您想要点击的Button中的属性,则可以将sender投射到Button并阅读其信息。像这样:

var buttonText = ((Button)sender).Text;

答案 1 :(得分:0)

您应该能够提供第二份表格,prvek,您可以从第一份表格中设置的财产。例如:

public string Element { get; private set; };

然后,在button_onClick方法中,您应该能够执行以下操作:

ElementForm myForm = new ElementForm(); //Whatever the class name is of your second form
myForm.Element = ((Button)this).Name; //Get the name of the button
myForm.Show();

在第二种形式的构造函数或初始化方法中,您需要设置表单的标题:

public ElementForm()
{
    InitializeComponent()
    this.Text = Element;
}