vb.net 根据该文本框的字符串更改文本框的前景色
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31955118/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Change the forecolor of textbox according to the string of that textbox
提问by Cary Bondoc
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.
到目前为止我可以通过if-else,我觉得这不是最有效的方式来做各种颜色。
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?
问题:我可以在不使用 if else 的情况下做到这一点吗?我的意思是系统可以检测到字符串并依靠该字符串来改变它的前景色或类似的东西吗?
回答by sujith karivelil
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:
当然,您不需要执行诸如按钮单击之类的附加事件,您可以在 text_change 事件本身中处理此问题。it will not throws any exception if the text is not a valid colour,just maintain the predefined color. 你可以这样做:
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).
根据MSDN,预定义颜色也称为已知颜色,由KnownColor 枚举的元素表示。如果 name 参数不是预定义颜色的有效名称,FromName 方法将创建一个 Color 结构,该结构的 ARGB 值为 0(即所有 ARGB 分量均为 0)。
回答by Robert Allen
TextBox1.ForeColor = Color.fromname(textbox1.text)


