Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How to change label on form in a different class in the same project

Status
Not open for further replies.

paulcy82

Programmer
Jan 25, 2005
28
0
0
US
I have one proj with 5 class. I want to change a label at runtime in one of the classes that the form is not declared in. I cannot use ME, and I have tried DirectCast(Form.ActiveForm, Form1).lblRpt.Text = "Opening CO Report". I know that I could declare a new instance of the class that the form is in, but I am wondering if there is another way.
 
Code:
DirectCast(Form.ActiveForm, Form1).lblRpt.Text = "Opening CO Report"
Should work if the form is on the top of all forms and you declared the label as friend or public.

Another way (and better, I think) is:
Code:
Public Class Class2

    Private m_MyForm As Form1

    Public Sub New(ByVal TheForm As Form1)

        m_MyForm = TheForm

    End Sub


    Public Sub MySub()

        m_MyForm.Label1.Text = "123"

    End Sub

End Class
Pass the instance of the form to the class in the constructor. Do not create another instance of the form.
 
or on the form that you want to alter the label on:
Code:
Class Form1
 Public sub SetLabel(Value as string)
   me.label1.text = value
 end sub
end class

which could be called from anywheres the form object is in scope:
Code:
Class Form2
 private sub OpenForm1()
   dim frm1 as form1
   frm1.SetLabel("Woot Woot L33+ Label!")
   frm1.showmodal(me)
 end sub
end class


or, do it the late binding way using only form2:
Code:
Class Form2
 private sub OpenForm1()
  dim frm1 as form1
  dim lbl as label
  
  lbl = callbyname(frm1, "label1", get) 
'get isn't the correct word, 
'there is an enumeration that should pop up w/
'intellisence, pick the one that sounds "get" like.

  if not lbl is nothing then 
   lbl.text = "Woot Woot L33+ Label!"
  end if

  frm1.showmodal(me)
 end sub
end class

-Rick

----------------------
 
The big limitation is to make sure you're running in the same thread as the form. If you're not, you need to do your updates asynchronously, or not at all.

Chip H.


____________________________________________________________________
Click here to learn Ways to help with Tsunami Relief
If you want to get the best response to a question, please read FAQ222-2244 first
 
ohhh! I just got to play with that code Chip! I was thinking of throwing together a FAQ for threading and updating the GUI from other threads. loads of fun. That's why I've been absent lately, uber deadlines and wicked cool multithreading code ;)

-Rick

----------------------
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top