how i can search inside a lot of labels text and t

2019-09-18 14:30发布

Quick question how can I search text inside 60 labels.text and the label color will change. Thanks in advance and I appreciate the help last time

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

Is there an easier way ?

2条回答
祖国的老花朵
2楼-- · 2019-09-18 15:16

You need to create an list of labels and add all the labels in the array during Form_Load. Then you need to loop thru the array and compare the text of each label with the txt1.Text and change the color of the label if condition matches.

Following is the sample code for this.

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

This should resolve your issue.

查看更多
Viruses.
3楼-- · 2019-09-18 15:17

Following the answer provided by @Chetan_Ranpariya and translating the code to VB.Net (with a small tweak) it would be something like this:

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

Basically for this you need a List of Tuple which is more efficient since every control has a pair. Inside the For Each statement you can include an Else clause to change the color to another one (I think this is to indicate the user the required fields on a form)
Give it a try and let me know your comments

查看更多
登录 后发表回答