Cary Bondoc
Cary Bondoc

Reputation: 2986

Change the forecolor of textbox according to the string of that textbox

Is it possible to create an application that can change the fore-color of the textbox (and thereby changing the color of the text inside that textbox) depending on the text inside that textbox upon clicked of the button?

So far I can do it via if-else, and I feel that this is not the most efficient way to do all kinds of color.

enter image description here

I have this code

Public Class Form1

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    If TextBox1.Text = "red" Then
        TextBox1.ForeColor = Color.Red
    ElseIf TextBox1.Text = "green" Then
        TextBox1.ForeColor = Color.Green
    End If
End Sub

End Class

Question: Can I do this without using if else? I mean can the system detects the string and rely on that string to change its fore-color or something like that?

Upvotes: 2

Views: 16967

Answers (2)

Robert Allen
Robert Allen

Reputation: 152

TextBox1.ForeColor = Color.fromname(textbox1.text)

Upvotes: 0

sujith karivelil
sujith karivelil

Reputation: 29036

Sure, You need not do an additional event like button click, you can handle this in text_change event itself.it will not throws any exception if the text is not a valid colour,just maintain the predefined color. you can do like this:

  Private Sub TextBox1_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox1.TextChanged
        TextBox1.ForeColor = Color.FromName(TextBox1.Text)
  End Sub

According to MSDN, A predefined color is also called a known color and is represented by an element of the KnownColor enumeration. If the name parameter is not the valid name of a predefined color, the FromName method creates a Color structure that has an ARGB value of 0 (that is, all ARGB components are 0).

Upvotes: 3

Related Questions