I have a form called Form1. In it, I have a button called Encrypt. When I hit that button I invoke a method in a different class. I want that method to change the value of textBox1.text but nothing happens when I use this code
in Form1 class
public string txtbox1
{
get
{
return textBox1.Text;
}
set
{
textBox1.Text = value;
}
}
in a method in the other class
Form1 textboxes = new Form1();//creating object of the Form1 class
textboxes.txtbox1= "whatever";
Nothing changes in the first text box. It’s like I don’t press anything at all!!!
Any help would be very appreciated
In your other class, you need a reference to the Form on which the button was clicked (and that has your existing text-boxes), not a new form.
This new form you’re instantiating isn’t the one that you’re looking at on the screen where you clicked your button.
(I’m assuming your event handler exists within the Form1 class, and that it then “forwards” information out to other class’s method as required? If not… it should!)
The button reference will be obtainable through the
senderobject and theevent argspassed to your event handler. You can pass a reference to the currentForm1instance by passing thethiskeyword to your other class’s method. Or you could pass thesenderif that’s useful to you, or just pass an explicit reference to the specific text box through to your other method.eg, to pass a reference to the form to your other method:
eg, to pass a reference to explicit text box to your other method:
eg, to pass the event object to your other method:
Also, stick a break point on your “other method” to ensure this code is even being fired. If not, go back to your event-handler, ensure that’s being fired. If not, check your event wire-up.
Although in all cases you need to be careful of the protection level on the control you want to update… you’ll need to make it public, internal, or protected depending on the relationship between your form and the other class, if you want to update it from outside your
Form1class.A better OO approach would be to have a method on
Form1that allows other classes to tellForm1to update the control for them (egupdateTextBox(string newText)). Because it’s not OO best-practice allow external objects to act on the members of your classes directly (as this requires knowledge of the internal structure of your class… which should be encapsulated so that your implementation can change without breaking the interface that exists between your class and the outside world).EDIT:
Actually, on re-reading your question, you do already encapsulate your text boxes using get/set properties. Nice. So you should pass the reference to your Form to your other method, and then update the form’s text via the property. Have added this method to the examples above.