问题描述
在 Visual C# 中,当我单击一个按钮时,我想加载另一个表单.但在该表单加载之前,我想用一些文本填充文本框.我试图在显示表单之前输入一些命令来执行此操作,但我收到一条错误消息,指出文本框由于其保护级别而无法访问.
In Visual C# when I click a button, I want to load another form. But before that form loads, I want to fill the textboxes with some text. I tried to put some commands to do this before showing the form, but I get an error saying the textbox is inaccessible due to its protection level.
如何在显示之前在表单中设置文本框?
How can I set the textbox in a form before I show it?
private void button2_Click(object sender, EventArgs e)
{
fixgame changeCards = new fixgame();
changeCards.p1c1val.text = "3";
changeCards.Show();
}
推荐答案
在按钮单击事件处理程序中创建新表单时,实例化一个新表单对象,然后调用它的 show 方法.
When you create the new form in the button click event handler, you instantiate a new form object and then call its show method.
一旦有了表单对象,您还可以调用该类中存在的任何其他方法或属性,包括设置文本框值的属性.
Once you have the form object you can also call any other methods or properties that are present on that class, including a property that sets the value of the textbox.
因此,下面的代码向 Form2 类添加了一个属性,用于设置您的文本框(其中 textbox1 是您的文本框的名称).我更喜欢这种方法方法,而不是通过修改其访问修饰符使 TextBox 本身可见,因为它为您提供了更好的封装,确保您可以控制文本框的使用方式.
So, the code below adds a property to the Form2 class that sets your textbox (where textbox1 is the name of your textbox). I prefer this method method over making the TextBox itself visible by modifying its access modifier because it gives you better encapsulation, ensuring you have control over how the textbox is used.
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
public string TextBoxValue
{
get { return textBox1.Text;}
set { textBox1.Text = value;}
}
}
在第一个表单的按钮单击事件中,您可以使用如下代码:
And in the button click event of the first form you can just have code like:
private void button1_Click(object sender, EventArgs e)
{
Form2 form2 = new Form2();
form2.TextBoxValue = "SomeValue";
form2.Show();
}
这篇关于如何在 Visual C# 中更改另一个窗体上的文本框中的文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!