Are there several objects in the With statement in VB?

I have many shortcuts in VB that I use in the With statement to set their properties.

Problem Is there a way to do something like the following:

 With lblA, lblB, lblC .fontColor = color.Red End With 

Is this possible, or do I need to manually execute the With statement for each of them?

+4
source share
3 answers

I would save these types of elements in a list, and then apply every cycle for them, assuming that they are all of the same type (or at least the base type). Assuming you are using label controls, this would be a solution. Note that I changed .fontColor to .ForeColor so that this example works with the Label class:

 Dim lblList as new List(of Label) ({lblA, lblB, lblC}) lblList.ForEach(sub(x) x.Fore Color = color.red) 

Since you posted your solution, you can still do the following to avoid iterating through the array you made (which is why I am doing this as a list), not taking into account the size of the array or something else:

  lblList.ForEach(Sub(x) With x .BackColor = Color.Black .Dock = DockStyle.Top .TextAlign = ContentAlignment.MiddleCenter End With End Sub) 
+4
source

There is a shorter and more readable version of your solution:

 For Each lbl As Label In {lblA, lblB, lblC} With lbl '... End With Next 
+5
source

Here is how I did it:

 Dim arrayMe As Label() = {lblA, lblB, lblC} For count = 0 To arrayMe.Length - 1 Step 1 With arrayMe(count) .BackColor = Color.Black .Dock = DockStyle.Top .TextAlign = ContentAlignment.MiddleCenter End With Next 

There are other ways to do this, but I found this to be useful.

0
source

Source: https://habr.com/ru/post/1446837/


All Articles