Ryan Ryan - 2 years ago 64
Vb.net Question

Creating a button that changes Label ForeColor with each click

Here's what I'm trying to do. I have a label named "lblWelcome", and a button named "btnTextColor". What I want the button to do is change the labels forecolor each time the button is clicked. Each time the button is pressed the forecolor of the label will change to a different color than before. That is what I want.

Here is what I've tried. Side note: I only put Red, Blue, and Black just as a start, so I could try the button and see if it works. My first hope was to get the button to choose a random color each time it's clicked. That would be perfect. Otherwise, just going through a list of colors one by one would be fine as well.

Private Sub btnTextColor_Click(sender As Object, e As EventArgs) Handles btnTextColor.Click
lblWelcome.ForeColor = Color.Red
lblWelcome.ForeColor = Color.Blue
lblWelcome.ForeColor = Color.Black

End Sub

With the above code, when I run the program, the button changes the labels forecolor to black. It just follows the last line of code. So, I went to the internets, looked for a solution, some bit of code I'm missing here. I found something called a "string", but it wasn't in reference to forecolor and I wasn't sure what to think or do. I'm just kind of stuck, I need to know what to add to make this button work the way I intended it to. But most importantly, I want to know how the solution I find works. For example, when someone tells me what to type, I'll fix my button, but I haven't learned the meaning of what I typed. I want to learn. So please, explain it a little bit when you reply to this. Just a little bit, that's all I ask. What command am I looking for? How do I use it? What does it do?

Answer Source

This should work for you.

Private Sub btnTextColor_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnTextColor.Click
    Static m_Rnd As New Random
    lblWelcome.ForeColor = Color.FromArgb(255, m_Rnd.Next(0, 255), m_Rnd.Next(0, 255), m_Rnd.Next(0, 255))
End Sub
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download