Change the forecolor of textbox according to the string of that textbox
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).
Cary Bondoc
SOreadytohelp #SOreadytohelp I am a professional software developer with more than 2 years of experience. Also, I am still on the process of knowing stackexchange process, so forgive me for asking ang answering low-quality questions. I loved to make the internet a better place! LinkedIn Profile
Updated on June 04, 2022Comments
-
Cary Bondoc almost 2 years
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?