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
 Next

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

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
        code
    End If
Next

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)()

thread solved

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.