是否可以创建一个应用程序,可以根据单击按钮时文本框内的文本来更改文本框的前景色(从而更改文本框内文本的颜色)?
到目前为止我可以通过if-else
来完成,我觉得这不是做各种颜色的最有效的方法。
我有这个代码
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
下课
问题:我可以在不使用 if else 的情况下执行此操作吗?我的意思是系统可以检测到该字符串并依赖该字符串来更改其前景色或类似的东西吗?
最佳答案
当然,您不需要执行像按钮单击这样的额外事件,您可以在 text_change 事件本身中处理它。如果文本不是有效颜色,它不会抛出任何异常,只需保持预定义的颜色
.你可以这样做:
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).
关于vb.net - 根据文本框的字符串更改文本框的前景色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31955118/