在您的其他类中,您需要对单击按钮的表单(并且具有您现有的文本框)的引用,而不是 new 表单。
您正在实例化的这个新表单不是您在单击按钮的屏幕上看到的那个。
(我假设您的事件处理程序存在于 Form1 类中,然后它会根据需要将信息“转发”到其他类的方法?如果不是......它应该!)
按钮引用可通过sender 对象和传递给事件处理程序的event args 获得。您可以通过将this 关键字传递给其他类的方法来传递对当前Form1 实例的引用。或者,如果这对您有用,您可以传递 sender,或者只是将对特定文本框的显式引用传递给您的其他方法。
例如,将对表单的引用传递给您的其他方法:
// Event handler on your form
private void button1_Click(object sender, EventArgs e)
{
ButtonWasPressedOnForm(this);
}
// Other method in your other class
public void ButtonWasPressedOnForm(Form formWhereButtonPressed)
{
// To act on the text box directly:
TextBox textBoxToUpdate = (TextBox)formWhereButtonPressed.Controls.Find("textBox1");
textBoxToUpdate.Text = "whatever";
// Or, using the Form1.txtBox1 property.
formWhereButtonPressed.txtBox1 = "whatever";
}
例如,将对显式文本框的引用传递给您的其他方法:
// Event handler on your form
private void button1_Click(object sender, EventArgs e)
{
ButtonWasPressedOnForm(textBox1);
}
// Other method in your other class
public void ButtonWasPressedOnForm(TextBox textBoxToUpdate)
{
textBoxToUpdate.Text = "whatever";
}
例如,将事件对象传递给您的其他方法:
// Event handler on your form
private void button1_Click(object sender, EventArgs e)
{
Button clickedButton = (Button)sender;
ButtonWasPressedOnForm(clickedButton);
}
// Other method in your other class
public void ButtonWasPressedOnForm(Button clickedButton)
{
Form theParentForm = clickedButton.FindForm();
// To act on the text box directly:
TextBox textBoxToUpdate = (TextBox)theParentForm.Controls.Find("textBox1");
textBoxToUpdate.Text = "whatever";
// Or, To act on the text box, via the form's property:
theParentForm.txtBox1 = "whatever";
}
另外,在您的“其他方法”上设置一个断点,以确保此代码甚至被触发。如果没有,请返回您的事件处理程序,确保它被触发。如果没有,请检查您的活动线路。
尽管在所有情况下,您都需要注意要更新的控件的保护级别...您需要将其设为公开、内部或受保护,具体取决于您的表单和其他类之间的关系, 如果你想从 Form1 类之外更新它。
更好的 OO 方法是在Form1 上有一个方法,允许其他类告诉Form1 为它们更新控件(例如updateTextBox(string newText))。因为这不是面向对象的最佳实践,所以允许外部对象直接作用于类的成员(因为这需要了解类的内部结构......应该封装,以便您的实现可以在不破坏现有接口的情况下进行更改在你的班级和外界之间)。
编辑:
实际上,在重新阅读您的问题时,您确实已经使用 get/set 属性封装了您的文本框。好的。因此,您应该将对您的表单的引用传递给您的其他方法,然后通过该属性更新表单的文本。在上面的例子中添加了这个方法。