LINQ Cookbook, Recipe 1: Change the font for all labels on a windows form (Kit George)

LINQ Cookbook, Recipe 1: Change the font for all labels on a windows form (Kit George)

  • Comments 5

Folks, we’re gonna start a ‘cookbook’ of LINQ entries, which we’ll be building over time. This is just meant to be a series of solutions to specific scenarios, that the team comes across when writing code and using queries. I can't think of a better way to communicate everything you might use LINQ for!

 

The point of the series is to show you the wide array of things LINQ can do. Like any good cookbook, we’ll have categories for the cookbook, so you can easily find items later. Don’t expect any particular ‘recipe’ to have a large description, although they will contain repro steps. Feel free to ask for any recipes you want to see, and we’ll get as many created as we can!

 

Ingredients:

-          Visual Studio 2008 (Beta2 or Higher)

 

Categories:

      -     LINQ-To-Objects, LINQ with Windows Forms, LINQ with controls, Label

 

Instructions:

-          Open Visual Studio 2008, and click ‘File/New Project’. Find and double-click the ‘Windows Forms Application’ Icon

-          Increase the size of the window to be large enough to fit a number of controls

-          Drag and drop multiple controls from your toolbox onto the form. Ensure at least 3-4 labels are added

o   My own personal favorites are two group boxes, with two labels in front on textboxes (and labels above the group boxes), and a couple of radio buttons in each. This ensures the recursive code is tested

-          Add a button to the form and change the text of the button to ‘Go’. Double-click the button, and modify the EventHandler code and add the method below:

 

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

        For Each label In GetLabels(Me)

            label.Font = New Font("Comic Sans MS", 12, _

                                  FontStyle.Bold Or FontStyle.Underline)

        Next

    End Sub

 

    Private Function GetLabels(ByVal sourceControl As Control) _

                               As IEnumerable(Of Control)

        If sourceControl.Controls.Count > 0 Then

            Dim labels = From cont As Control In sourceControl.Controls _

                         Where TypeOf cont Is Label _

                         Select cont

 

            For Each c As Control In sourceControl.Controls

                labels = labels.Union(GetLabels(c))

            Next

 

            Return labels

        End If

 

        Return New List(Of Control)

    End Function

 

-          Change the ‘New Font’ line to be the style of your choice

Leave a Comment
  • Please add 1 and 3 and type the answer here:
  • Post
Page 1 of 1 (5 items)