Reputation: 51
Here is my code that should change the back color of any of my buttons, but it doesn't work and I don't have any idea what's wrong:
Public Sub color(ByVal backcolor As System.Drawing.Color)
backcolor = Drawing.Color.CadetBlue
End Sub
And here is how I call it when a button was clicked. It should change the back color of Button1
, but it doesn't. Am I doing it right or am I missing something?
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
color(Button1.BackColor)
End Sub
Upvotes: 1
Views: 444
Reputation: 27342
You could create an extension method to do this. Create a public module as follows:
Public Module Module1
<Runtime.CompilerServices.Extension()>
Public Sub SetBackColourToCadetBlue(aButton As Button)
'Use the following line for Telerik Button
'Public Sub SetBackColourToCadetBlue(aButton As Telerik.WinControls.UI.RadButton)
aButton.BackColor = Color.CadetBlue
End Sub
End Module
The you can just call the following to set the backcolor of any button:
Button1.SetBackColourToCadetBlue()
Upvotes: 1
Reputation: 752
Public Sub color(ByVal btn As Control, ByVal clr As System.Drawing.Color)
btn.BackColor = clr
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
color(Button1, Drawing.Color.CadetBlue)
End Sub
Or
Public Sub color(ByVal btn As Control)
btn.BackColor = Drawing.Color.CadetBlue
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
color(Button1)
End Sub
That works with any control (Textboxes, Labels e.t.c)
Upvotes: 1
Reputation: 11216
System.Drawing.Color
is a value type (structure). When you pass it to your color
method, only a copy is passed and your method only changes the copy. You should change your Sub to a Function and return the color and assign it to the button's BackColor
property:
Public Function color() As System.Drawing.Color
Return System.Drawing.Color.CadetBlue
End Function
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Button1.BackColor = color()
End Sub
Although that function doesn't add any value. You should probably just set the color directly:
Button1.BackColor = System.Drawing.Color.CadetBlue
Per @VisualVincent's comment, you can use ByRef
in your Sub:
Private Sub ChangeColor(ByRef c As System.Drawing.Color)
c = Color.CadetBlue
End Sub
Upvotes: 1