user3516240
user3516240

Reputation: 375

Accessing label on Passed Form

I'm trying to add an activity logger into my application. I'm hoping to keep my code clean and so only want to state the current activity once in my code and then it displays it in lblStatus and updates the log file. I'm trying to do this like this:

I'm passing it like this on my normal form:

LogActivity.LogActivity(Me, "Checking program directories...")

And this is the sub that's doing the work.

Public Sub LogActivity(FormID As Form, ByVal ActivityDescription As String)

'Log Activity code is here

'Update Status Label on form 
FormID.lblStatus = ActivityDescription

end sub

But Visual Studio doesn't understand the syntax, I can understand why but I'm not sure how to do this correctly.

'lblStatus' is not a member of 'Form'

However, all my forms will call this sub, so I really need my code to understand which form called the sub and to update the lbl on that form specifically.

I could just check the form's name like this:

If Form.Name = "Main_Loader" Then 
Main_Loader.lblStatus = ActivityDescription
elseif Form.Name = "..." then
end if 

But again that's not very clean and doesn't seem like the proper way... Could anyone advise?

Upvotes: 0

Views: 33

Answers (2)

Idle_Mind
Idle_Mind

Reputation: 39132

Assuming the Label is called "lblStatus" on ALL of the Forms, you could simply use Controls.Find() like this:

Public Sub LogActivity(FormID As Form, ByVal ActivityDescription As String)
    Dim matches() As Control = FormID.Controls.Find("lblStatus", True)
    If matches.Length > 0 AndAlso TypeOf matches(0) Is Label Then
        Dim lbl As Label = DirectCast(matches(0), Label)
        lbl.Text = ActivityDescription
    End If
End Sub

Upvotes: 1

OneFineDay
OneFineDay

Reputation: 9024

You could use a custom event. The form that needs the info reported back subscribes to the event that is on the form that has the LogActivity.

Public Class frmActivity 'name of class is an example
  Private log As New LogClass
  Public Event LogActivity(ActivityDescription As String, log As LogClass)
  'somewhere in code raise this event and send to info to main form
  Private Sub SomeEventSub()
     RaiseEvent LogActivity("some status", log)
  End Sub
  '...
End Class

Public Class frmMain 'name of class is an example
  Private Sub btnGetActivity() Handles btnGetActivity.Click
    Dim frm As New frmActivity
    Addhandler frm.LogActivity, AddressOf LogActivity
    frm.Show()
  End SUb
  Private Sub LogActivity(ActivityDescription As String, log As LogClass)
    lblStatus = ActivityDescription
    'then use the log variable to store the log data
  End Sub
  '...
End Class 

Upvotes: 1

Related Questions