System windows controls label

System windows controls label

Windows Controls: The Label

Introduction to Labels

Description

A label is a control that serves as a guide to the user. It provides static text that the user cannot change but can read to get information on a form. The programmer can also use it to display simple information to the user. Most controls on the form are not explicit at first glance and the user may not know what they are used for. Therefore, you can assign a label to a control as a help to the user.

Creating a Label

To add a label to a container, click the Label button from the Toolbox and click the object that would host it.

To programmatically create a label, declare a handle to Label, initialize it using its default constructor, and add it to the Controls property of the form. Here is an example:

Topic Applied: Introducing Labels

  1. Start Microsoft Visual Studio
  2. Create a Windows Forms Application named ElementaryAddition1
  3. From the Common Control section of the Toolbox, click Label and click the form
  4. From the Common Control section of the Toolbox, click the Label again and click the form
  5. From the Common Control section of the Toolbox, click the Label again and click the form

Characteristics of a Label

The most important characteristic of a label control is the text it displays. That text is also referred to as its caption and this is what the user would read. The text of a label is its Text property and is its default. To set a label’s caption, after adding the control to a container, click Text in the Properties window and type the desired value. As we mentioned when studying controls characteristics, at design time, the text you type in the Text field is considered «as is»ќ. If you want to create a more elaborate and formatted string, you would have to do it programmatically. Here is an example:

Here is an example of what this would produce:

When it comes to its caption, one of the most valuable characteristics of the text of a label is the variance of the font. When designing a caption. you can change the default font to make it more attractive.

Topic Applied: Captioning the Labels

  1. On the form, click the first label
  2. In the Properties window, click Text and type 00
  3. Click (Name) and type lblOperand1
  4. Click TextAlign and the arrow of its combo box to select MiddleCenter
  5. Click the + button of the Font field and change the characteristics as follows:
    Name: Tahoma
    Font Style: Bold
    Size: 48
  6. On the form, click the second label and, in the Properties window, change its characteristics as follows:
    Text: +
    TextAlign: MiddleCenter
    (Name): lblOPeration
    Font -> Name: Arial
    Font -> Font Style: Bold
    Font -> Size: 48
  7. On the form, click the third label and, in the Properties window, change its characteristics as follows:
    Text: 00
    TextAlign: MiddleCenter
    (Name): lblOperand2
    Font -> Name: Arial
    Font -> Font Style: Bold
    Font -> Size: 48

Automatically Sizing a Label

After adding a label to a form, by default, it receives a fixed size. If you type its caption and press Enter, the text you provided would be confined to the allocated dimensions of the control. If the text is too long, part of it may disappear. You can then resize the label to provide more area. Another solution is to automatically resize the label to accommodate the length of the string you typed. This is aspects is controlled by the Boolean AutoSize property. Its default value is False. If you set this property to True, at design time, a rectangular border appears around it. If you type a string in the Text field and press Enter, the control would be resized to show the whole string but using only the necessary space.

If you programmatically create a label, it assumes a default size. If you assign it a string that is too long for that default size, part of the string may appear on a subsequent line. If you want the whole string to appear on the same line, you can set the AutoSize to true. Here is an example:

Here is an example of what this would produce:

Topic Applied: Using AutoSize

  1. Click an unoccupied area of the form and press Ctrl + A to select all three labels
  2. In the Properties window, double-click AutoSize to set the value to False

After typing the caption of a label whose AutoSize property is set to False, you can resize its allocated space to your liking. This is because a string occupies a rectangular area. Here is an example:

By default, the caption of a label is positioned starting on the middle-left side of its allocated rectangle. Alternatively, you can position it to one of the nine available positions. The position of the caption of a label is controlled by the TextAlign property which is based on the ContentAlignment enumerator:

It can have the following values:

TopLeft TopCenter TopRight
MiddleLeft MiddleCenter MiddleRight
BottomLeft BottomCenter BottomRight

Pictures on a Label

Other fancy characteristics you can apply to a label include its font and color. For example, a label is primarily meant to display a string. To make it fancier, you can display a (small) picture next to it. To do this, at design time, use the Image field of the Properties window to select a picture. You can also specify the picture at run time by assigning an Image value to the Label.Image property. After adding a picture that would accompany the label, you can specify what position the picture would hold with regards to the label. To do this, select the desired position of the ImageAlign field in the Properties window.

Instead of using a picture from the Image property, you can create a list of images using an ImageList control and assign it to the label. In fact, the advantage of an ImageList is that, unlike the Image property, it allows you to use more than one picture.

After assigning an ImageList to the label control using the Properties window or code, you can use the ImageIndex to specify what picture to display next to the label.

A Label’s Mnemonic

A label provides another property called UseMnemonic. This property is valuable only when the label accompanies another control.

Topic Applied: Using a Text Box

  1. Complete the design of the form as follows:
    Control Text Name TextAlign Font Additional Properties
    Label 00 lblOperand1 Center Name: Tahoma
    Font Style: Bold
    Size: 48
    ForeColor: Blue
    Label + Center Name: Arial
    Font Style: Bold
    Size: 48
    ForeColor: Maroon
    Label 00 lblOperand2 Center Name: Tahoma
    Font Style: Bold
    Size: 48
    ForeColor: Blue
    Label = Center Name: Arial
    Font Style: Bold
    Size: 48
    ForeColor: Green
    Label 00 lblResult Center Name: Tahoma
    Font Style: Bold
    Size: 48
    Label New Operation lblNewOperation Center Name: Tahoma
    Font Style: Bold
    Size: 28
    BorderStyle: Fixed3D
    ForeColor: White
    BackColor:Maroon
    Label Quit lblQuit Center Name: Tahoma
    Font Style: Bold
    Size: 28
    BorderStyle: FixedSingle
  2. To be able to use the Visual Basic library, in the Solution Explorer, right-click References and click Add Reference.
  3. In the Reference Manager, click the chek box of Microsoft.VisualBasic

  • Click OK
  • Double-click New Operation and implement its event as follows:
  • Return to the form and double-click Quit
  • Implement its event as follows:
  • Execute the application and test it
  • Click the Close button to close the form and return to your programming environment
  • Labels and Data Record Selection

    Text-based controls are the prime candidate for showing the value of a column of a table. Probably the simplest way to do this is by assigning a value gotten from a SQL data reader. Here is an example:

    An alternative is to use the Binding class. In this case, you must access the DataBindings property of the label and call the Add() method of the property. In the parentheses, use the primary constructor of the class to pass the Text property as a string, the index of the first table of the data set, and the name of the column of the table. This can be done as follows:

    Label. Target Свойство

    Определение

    Получает или задает элемент, который получает фокус, когда пользователь нажимает клавишу доступа метки. Gets or sets the element that receives focus when the user presses the label’s access key.

    Значение свойства

    Элемент UIElement, который получает фокус, когда пользователь нажимает клавишу доступа. The UIElement that receives focus when the user presses the access key. Значение по умолчанию — null . The default is null .

    Примеры

    В следующем примере показано, как задать свойство Target объекта Label. The following example shows how to set the Target property of a Label.

    Комментарии

    Вы можете указать сочетания клавиш для элементов, которые не поддерживают ключи доступа, указав Label ключ доступа и установив это свойство. You can provide keyboard shortcuts to elements that don’t support access keys by giving a Label an access key and setting this property. Присвойте метке ключ доступа, поместив знак подчеркивания непосредственно перед символом, который выступает в качестве клавиши доступа. Assign an access key to a label by placing an underscore immediately before the character that acts as the access key. Ключ доступа можно указать в Content свойстве или с помощью параметра Content для AccessText объекта. An access key can be specified in the Content property or by setting Content to an AccessText object.

    Это свойство нельзя использовать для определения UIElement . You cannot use this property to define a UIElement. Например, следующий код компилирует, но не работает: . For example, the following compiles but is not functional: . Это свойство предоставляет ссылку на элемент, который уже определен в приложении. This property provides a reference to an element that is already defined in your application.

    Сведения о свойстве зависимостей Dependency Property Information

    Поле идентификатора Identifier field TargetProperty
    Свойства метаданных, для которых задано значение true Metadata properties set to true Нет None

    Использование атрибута XAML XAML Attribute Usage

    Использование элемента свойства XAML XAML Property Element Usage

    Значения XAML XAML Values

    nameOfExistingElement
    Имя UIElement , которое получает фокус при нажатии клавиши доступа. The name of UIElement that receives focus when the access key is pressed.

    Читайте также:  Перенос лицензии windows 10 при замене диска
    Оцените статью