第一次检查时,我猜测这将是一项简单的任务(也许它仍然是!),但我遇到了困难。假设我有一个包含1000个文本框的表单,其中每个文本框包含随机分布,但在许多情况下匹配字符串。例如,如果有1000个文本框,则可以在任何一个中找到以下内容:
AAAA-XXXX
AAAA-XXXX
BBBB-XXXX
BBBB-XXXX
CCCC-XXXX
CCCC-XXXX
...
我如何循环文本框,识别所有匹配的示例并突出显示匹配的textbox.backcolor?对于完全匹配,背景颜色应该相同,但对于每个唯一匹配集,背景颜色不同。可能有多达100套不同!
答案 0 :(得分:1)
你可以这样做
Dim strText As String
For Each TextBox1 As System.Windows.Forms.TextBox In Me.Controls
strText = TextBox1.Text
For Each TextBox2 As System.Windows.Forms.TextBox In Me.Controls
If strText = TextBox2.Text AndAlso TextBox2.Name <> TextBox1.Name Then
TextBox2.BackColor = Color.Red ' or whatever you want to use
TextBox1.BackColor = Color.Red
End If
Next
Next
答案 1 :(得分:1)
只是将一个正在运行的测试项目鞭打在一起,这是我采取的一种方法。它避免了将每个文本框与每个其他文本框进行比较。我已经为你评论了一切:)
Private Sub SetBoxColors()
'The keys are textbox texts, the values are the number of times it occurs
Dim UniqueTextsAndUsage As New Dictionary(Of String, Integer)
Dim FirstInstanceTextBoxes As New List(Of TextBox)
'The keys are textbox texts, the values are the colour for the box
Dim UniqueColors As New Dictionary(Of String, System.Drawing.Color)
'Iterate over all the text boxes
' Substitute Me for your Form instance if necessary
For Each TBox As Control In Me.Controls
'Skip things that aren't textboxes
If Not TypeOf TBox Is TextBox Then
Continue For
End If
'If we have seen this textbox text before
If UniqueTextsAndUsage.ContainsKey(TBox.Text) Then
'Increase the usage
UniqueTextsAndUsage(TBox.Text) += 1
If UniqueTextsAndUsage(TBox.Text) = 2 Then
'This is the second usage, generate a colour for this set of boxes
UniqueColors.Add(TBox.Text, GenerateColor(UniqueColors.Count + 1))
End If
'Colour this textbox
' (it won't get the first instance of each unique string)
TBox.BackColor = UniqueColors(TBox.Text)
Else
'We have NOT seen this textbox text before
'Add the first occurence of the text
UniqueTextsAndUsage.Add(TBox.Text, 1)
'Mark this textbox as one we may have to colour later
FirstInstanceTextBoxes.Add(TBox)
End If
Next
'Colour all the first instances
For Each TBox As TextBox In FirstInstanceTextBoxes
'Check there are sufficient uses of this text
If UniqueTextsAndUsage(TBox.Text) > 1 Then
TBox.BackColor = UniqueColors(TBox.Text)
End If
Next
End Sub
Private Function GenerateColor(Id As Integer) As System.Drawing.Color
'Needs more thought - often too dark
Dim KnownColourByIdNumber As System.Drawing.KnownColor = Id
Return System.Drawing.Color.FromKnownColor(KnownColourByIdNumber)
End Function
GenerateColor函数需要更多考虑,以便它生成一些更好的颜色,但我留给你。
您可能还需要重置,将每个框设置为DefaultControl颜色或其调用的任何颜色,并在SetBoxColors顶部运行它。