Accessing form objects
-
Hi, I am having a class Btree, its has function to print pre-order of binary tree on the form. problem is that, i am not able to access label on the form from this BTree.cs file. I made that label as public in form.cs file, even i am not able to access. can any one pls tell me, how can i access form objects from other class file.
-
Hi, I am having a class Btree, its has function to print pre-order of binary tree on the form. problem is that, i am not able to access label on the form from this BTree.cs file. I made that label as public in form.cs file, even i am not able to access. can any one pls tell me, how can i access form objects from other class file.
Your binary tree class (Btree) needs to get a reference to the Form class of which the label is on. There're a few different ways to handle the interaction between the two in regards to how loosely coupled you want them to be however the easiest thing to do would be to pass in a reference to the form object through the Btree constructor...
-
Your binary tree class (Btree) needs to get a reference to the Form class of which the label is on. There're a few different ways to handle the interaction between the two in regards to how loosely coupled you want them to be however the easiest thing to do would be to pass in a reference to the form object through the Btree constructor...
Hi Thanku 4 reply Can U pls give some example code. or refer me to the any tutorial.
-
Hi Thanku 4 reply Can U pls give some example code. or refer me to the any tutorial.
Sure, so if we had a label on the form that we wanted to update by code in some other class you would do the following: In your form code you would expose the label as a property...
delegate void Func();
...
public string MessageText
{
get
{
return label1.Text;
}
set
{
Func del = delegate
{
label1.Text = value;
};Invoke(del); }
}
Then we can create a new instance of the Btree class (in this case I'll just create it from the Load method of the form)
Btree myBtree = new Btree(this);
"this" refers to the Form class instance itself.. so for the constructor of the Btree class I'd have
public Btree(Form1 frm)
{
frm.MessageText = "This is a test";
}Since you have a reference to Form1 you can get/set properties and call methods on it. It is, however, better practice to create an interface that states what properties/methods the form should support of which other classes would make calls to so you dont tie yourself down to specific class/form names... but I dont think that would be a big concern for you at this point in time :P