Question : Changing the BackColor of a Button on a Form Through Code Placed in a Module

I have a Form1 in a Visual Studio 2008 Project with a   Button1    on it.
I would like to set the   BackColor  of this    Button1      through code put in a Sub in a Module1   in my Project.
I have the following code in Module1

Public Sub ChangeBackColor ()
MsgBox “Hello – Let us see if the Color of Button1 will change?”

Form1.Button1.BackColor = Color.RoyalBlue

End Sub

I have put a Call to ChangeBackColor() in the load event of Form1
I had hoped that when Form1 Loads  it will call ChangeBackColor and through this the color of Button1 on Form will change to RoyalBlue.
However this is not working. I wish to know whether what I was expecting to happen was unrealistic and if there is way of achieving what I wanted to achieve – that is changing the BackColor of a Button on Form1   through a   Sub put in another  Module in your Project.
As a test whether the call to ChangeBackColor was working, I have put a MsgBox in the
Sub ChangeBackColor and the MsgBox does  show up when Form1 Loads up but the Color of Button1 does not change. I would be grateful for help in achieving this.

Thank you for your help in anticipation.
Please note I am using Visual Basic in Visual Studio 2008.

Answer : Changing the BackColor of a Button on a Form Through Code Placed in a Module

Under what circumstances will the code in the Module be called?

One different approach is to instead iterate over the MdiChildren() property of your Main form and find the instance of Form1 that way:

    Public Sub ChangeBackColor()
        For Each child As Form In Main.MdiChildren
            If TypeOf child Is Form1 Then
                Dim f1 As Form1 = CType(child, Form1)
                f1.Button1.BackColor = Color.RoyalBlue
            End If
        Next
    End Sub

It looks like you already have a reference to your instance of Form1 via your "frm1" variable (probably at class level in Main?).  You could pass that into ChangeBackColor():

    Public Sub ChangeBackColor(ByVal f1 As Form1)
        f1.Button1.BackColor = Color.RoyalBlue
    End Sub

From within Main, you would do:

    ChangeBackColor(frm1)
Random Solutions  
 
programming4us programming4us