GetType.GetProperties for PictureBox

185 Views Asked by At

I am trying to run the code,in windows form using vb.net where I have multiple pictureboxes with properties like backgroudimage and location.

So I want to eliminate these repeated initilisations,and hence I am trying to initialise all the controls using GetType.Getproperties command. But I am getting an exception error

Private Sub Read_csv_file_itextbox_Load_1(sender As Object, e As EventArgs) Handles MyBase.Load
    For Each c As Control In Me.Controls
        If c.GetType().Name = "TextBox" Then
            c.GetType().GetProperty("BackColor").SetValue(c, "Transparent", Nothing)
        End If
    Next
End Sub

And I also need to explicitly set properties for some textboxes That have naming TextBox1,TextBox2, Textbox3 so on.

And I want to access these Textbox in their even number indexing and perform my code.

1

There are 1 best solutions below

7
On

The proper way to do what you're trying to do in the code you posted would be this:

For Each tb In Controls.OfType(Of TextBox)()
    tb.BackColor = Color.Transparent
Next

Don't use Reflection without good reason.

Note that setting the BackColor of a TextBox to Transparent doesn't necessarily make sense, but you can use this same principle on any type of control and any property and any value.

If you want to filter any list using LINQ then you call the Where method. It's up to you to determine what the condition(s) is that you want to filter by and write the appropriate Boolean expression, e.g.

For Each tb In Controls.OfType(Of TextBox)().
                        Where(Function(tb) Enumerable.Range(1, 10).
                                                      Where(Function(n) n Mod 2 = 0).
                                                      Select(Function(n) $"TextBox{n}").
                                                      Contains(tb.Name))
    tb.BackColor = Color.Transparent
Next

That will first generate a list of TextBoxes and then filter them on Name. It will include only those with a Name of TextBoxN where N is an even number in the range 1 to 10. This is a perfect example of determining the logic first, i.e. working out what the code needs to do, and then writing code to do that specifically.