Ron*_*ona 2 c# visual-studio-2010
我有一个名为Form1的表单.在其中,我有一个名为Encrypt的按钮.当我按下那个按钮时,我在另一个类中调用一个方法.我希望该方法更改textBox1.text的值,但是当我使用此代码时没有任何反应
public string txtbox1
{
get
{
return textBox1.Text;
}
set
{
textBox1.Text = value;
}
}
Run Code Online (Sandbox Code Playgroud)
Form1 textboxes = new Form1();//creating object of the Form1 class
textboxes.txtbox1= "whatever";
Run Code Online (Sandbox Code Playgroud)
第一个文本框中没有任何变化.这就像我根本不按任何东西!
任何帮助将非常感激
在您的其他课程中,您需要引用单击按钮的表单(并且具有现有的文本框),而不是新表单.
您实例化的这个新表单不是您在单击按钮的屏幕上查看的表单.
(我假设您的事件处理程序存在于Form1类中,然后它根据需要将信息"转发"到其他类的方法?如果不是......它应该!)
按钮引用可以通过sender对象获得并event args传递给事件处理程序.您可以Form1通过将this关键字传递给其他类的方法来传递对当前实例的引用.或者您可以传递sender对您有用的if,或者只是将对特定文本框的显式引用传递给您的其他方法.
例如,将表单的引用传递给您的其他方法:
// 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";
}
Run Code Online (Sandbox Code Playgroud)
例如,将显式文本框的引用传递给您的其他方法:
// 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";
}
Run Code Online (Sandbox Code Playgroud)
例如,将事件对象传递给您的其他方法:
// 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";
}
Run Code Online (Sandbox Code Playgroud)
另外,在"其他方法"上添加一个断点,以确保此代码被触发.如果没有,请返回事件处理程序,确保被触发.如果没有,请检查您的活动连线.
虽然在所有情况下你都需要注意你想要更新的控件的保护级别......你需要根据表单与其他类之间的关系将其设置为公共,内部或受保护,如果你想要从Form1课堂外更新它.
一个更好的面向对象方法是有一个Form1允许其他类告诉Form1更新控件的方法(例如updateTextBox(string newText)).因为它不是OO最佳实践允许外部对象直接作用于类的成员(因为这需要知道类的内部结构...应该封装,以便您的实现可以更改而不会破坏存在的接口你的班级和外界之间).
编辑: 实际上,在重新阅读您的问题时,您已经使用get/set属性封装了文本框.尼斯.因此,您应该将对Form的引用传递给其他方法,然后通过属性更新表单的文本.已将此方法添加到上面的示例中.