vb.net - 根据文本框的字符串更改文本框的前景色

标签 vb.net textbox uicolor

是否可以创建一个应用程序,可以根据单击按钮时文本框内的文本来更改文本框的前景色(从而更改文本框内文本的颜色)?

到目前为止我可以通过if-else来完成,我觉得这不是做各种颜色的最有效的方法。

enter image description here

我有这个代码

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/

相关文章:

ios7 - UIBarButtonItem setTintColor 在 iOS7 上不起作用

ios - 设置 View 的背景颜色时如何避免平铺?

vb.net - Endif 前面必须有匹配的 if

vb.net - 为什么 BindingList(Of T) 没有 AddRange 成员?

JavaScript 斐波那契计算器 : How to output answer into text box?

javascript - ASP.NET 4.5 文本框文本模式 'Date' 回发问题

javascript - 如何将 vb.net 变量加载到 JavaScript

mysql - 循环在 Sub 中不断重复

c# - 当内容超出范围时在文本框中显示滚动条C#

iphone - 从 UIColor 中提取 RGB