快速提问如何在60 labels.text
内搜索文字,标签颜色会发生变化。在此先感谢,我很感谢上次的帮助
dim Nc as color = color.RED
dim Oc as color = Color.Black
'' i need to search in multiple labels.text using txt1.text if possible
if txt1.text = label1.text then
laebl1.forecolor = Nc
End IF
有更简单的方法吗?
答案 0 :(得分:0)
您需要创建标签列表,并在Form_Load期间添加数组中的所有标签。然后你需要循环遍历数组并将每个标签的文本与txt1.Text进行比较,并在条件匹配时更改标签的颜色。
以下是此示例代码。
Public Partial Class Form1
Inherits Form
Private labels As List(Of Label)
Public Sub New()
InitializeComponent()
labels = New List(Of Label)()
labels.Add(label1)
labels.Add(label2)
labels.Add(label3)
labels.Add(label4)
labels.Add(label5)
labels.Add(label6)
labels.Add(label7)
End Sub
Private Sub button1_Click(sender As Object, e As EventArgs)
For Each label As Label In labels
If textBox1.Text = label.Text Then
label.ForeColor = Color.Red
End If
Next
End Sub
End Class
这可以解决您的问题。
答案 1 :(得分:0)
按照@Chetan_Ranpariya
提供的答案并将代码翻译为VB.Net
(稍加调整),就会出现这样的情况:
Imports System.Collections.Generic
Public Class Form1
Private lstControls As List(Of Tuple(Of TextBox, Label))
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
lstControls = New List(Of Tuple(Of TextBox, Label))
lstControls.Add(Tuple.Create(TextBox1, Label1))
lstControls.Add(Tuple.Create(TextBox2, Label2))
lstControls.Add(Tuple.Create(TextBox3, Label3))
lstControls.Add(Tuple.Create(TextBox4, Label4))
lstControls.Add(Tuple.Create(TextBox5, Label5))
lstControls.Add(Tuple.Create(TextBox6, Label6))
lstControls.Add(Tuple.Create(TextBox7, Label7))
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
For Each tuplePair As Tuple(Of TextBox, Label) In lstControls
If tuplePair.Item1.Text = tuplePair.Item2.Text Then
tuplePair.Item2.ForeColor = Color.Red
End If
Next
End Sub
End Class
基本上,你需要一个List of Tuple
,因为每个控件都有一对,所以效率更高。在For Each
语句中,您可以包含Else
子句以将颜色更改为另一个(我认为这是为了向用户指示表单上的必填字段)
试一试,让我知道你的意见