there are 10 labels and 1 button in the form and i want to set some properties using code(which will applicable to lable only) , and for this i used the code

 For Each lbl As Label In Form1.Controls
            lbl.Font = New Font("Arial", 12, FontStyle.Regular, GraphicsUnit.Point)
            lbl.Top = settop 
            lbl.Left = 40
            settop += 100

Now the error is

Unable to cast object of type 'System.Windows.Forms.Button' to type 'System.Windows.Forms.Label'.

how to solve that issue

Edited 3 Years Ago by Learner010

That's because your code is trying to cast every type of control present in the form into a label.

Try this:

For Each ctrl As control in Form1.controls
    If TypeOf ctrl is Label then
    End If

i already tried that code but the question is
when i have already defined (For Each lbl As Label) then why it is considering button also.

would you please tell about it ?

It attempts to retrieve every type of control in the form and cast it into a label. If you want to retrieve only Labels, use oftype.

For Each lbl As Label in Form1.Controls.OfType(Of Label)()

This question has already been answered. Start a new discussion instead.