简体   繁体   中英

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.

在此处输入图片说明

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?

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).

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM