-2

In C# Windows form application, how to find the label on the form which contains the text I'm looking for?

For example: I am trying to search a label whose Text property contains "25".

Ehsan Sajjad
  • 61,834
  • 16
  • 105
  • 160

1 Answers1

8

You can find it using linq this way:

var control =  this.Controls.OfType<Control>().Where(x => x is Label && x.Text.Contains("25"));

or as @Sayse suggested just filter on Label type:

var Labelcontrol =  this.Controls.OfType<Label>().Where(x => x.Text.Contains("25"));

Explanation:

If we want to fetch all controls of the form we have to do :

var AllControls = this.Controls.OfType<Control>();

and if we want to fetch only Controls of Type Label then:

var LabelControls = this.Controls.OfType<Label>();

Here this refers to current form of application.

UPDATE:

If you have label in nested controls, means inside some user control or some other control, then you need to check recrursively as in this SO post (How to get ALL child controls of a Windows Forms form of a specific type)

Community
  • 1
  • 1
Ehsan Sajjad
  • 61,834
  • 16
  • 105
  • 160