Other Software > Developer's Corner
Forms calls a class, class interacting with a form
mediaguycouk:
If I have a textbox in a form called 'textbox' and a class called 'class' is there any way of doing this?
Form1:
textbox.text = "";
Class class = new Class();
class.runfunction()
Class:
public void runfunction()
{
form1.textbox.text = "Some text"; // This would never work, but how could it?
}
rht341:
Hello,
There is more than one way to do this; one is to have the runfunction method take a TextBox as a parameter:
Form1:
textbox.text = "";
Class class = new Class();
class.runfunction(textbox)
Class:
public void runfunction(TextBox tx)
{
tx.text = "Some text"; // This would never work, but how could it?
}
mediaguycouk:
I never knew that, thanks.
Is it possible to do it in the class itself (so it is usable by all functions?)
Something like Class class = new Class(textbox);
rht341:
Yes, you have to declare a special constructor (New) and have a private variable in the class:
Public Class MyClass
private _tx as TextBox
Public Sub New(ByVal txtBox as TextBox)
_tx = txtBox
End Sub
Public Sub MyFunction(ByVal someText as String)
_tx.Text = someText
End Sub
End Class
CWuestefeld:
rht341 is certainly correct, but a couple of warnings:
1: In your proposal to put the reference to the textbox into your class's constructor, you've tied the life of the textbox to the life of your object. A reference to the textbox will keep it around as long as your class, and this may manifest itself as a memory leak, causing your program to die after having been active for some time.
2: In the 15-20 years that OO development has been popular, we've learned some lessons. Depending on the nature of your class, you may be about to step into one of the classic blunders. The most famous is never get involved in a land war in Asia, but only slightly less well-known is this: keep your application's data separate from its user interface. When things start to get bound together tightly, it becomes difficult to maintain your program as you need to make changes to either the UI or the data. Better to keep them separate, with a well-defined interface dictating how they interact. Probably the leading design for ensuring this is the Model-View-Controller pattern.
This same kind of question comes up in many areas, and developers have found many ways that work well for attacking them. These have been documented and gathered together in catalogs of "patterns" (e.g. here: http://www.dofactory.com/Patterns/Patterns.aspx ). You'll give yourself a big leg up if you read up on these. You'll get the benefit of many years of experience from developers that have gone before us.
Navigation
[0] Message Index
[#] Next page
Go to full version