Windows forms table layout panel

Содержание
  1. Step 4: Lay out your form with a TableLayoutPanel control
  2. How to lay out your form with a TableLayoutPanel control
  3. Next steps
  4. Пошаговое руководство. Упорядочение элементов управления в формах Windows Forms с помощью элемента TableLayoutPanel Walkthrough: Arranging Controls on Windows Forms Using a TableLayoutPanel
  5. Создание проекта Creating the Project
  6. Создание проекта To create the project
  7. Упорядочение элементов управления в строках и столбцах Arranging Controls in Rows and Columns
  8. Размещение элементов управления в строках и столбцах с помощью TableLayoutPanel To arrange controls in rows and columns using a TableLayoutPanel
  9. Размещение элементов управления внутри ячеек с помощью закрепления и привязки Positioning Controls Within Cells Using Docking and Anchoring
  10. Размещение элементов управления внутри ячеек Positioning controls within cells
  11. Установка свойств строк и столбцов Setting Row and Column Properties
  12. Задание свойств строк и столбцов To set row and column properties
  13. Объединение строк и столбцов с помощью элемента управления Spanning Rows and Columns with a Control
  14. Объединение строк и столбцов с помощью элемента управления To span rows and columns with a control
  15. Вставка элементов управления двойным щелчком по ним в панели элементов Inserting Controls by Double-clicking Them in the Toolbox
  16. Вставка элементов управления двойным щелчком по ним в панели элементов To insert controls by double-clicking in the Toolbox
  17. Автоматическая обработка перегрузок Automatic Handling of Overflows
  18. Наблюдение за автоматической обработкой перегрузок To observe automatic handling of overflows
  19. Вставка элемента управления путем рисования его контура Inserting a Control by Drawing Its Outline
  20. Вставка элемента управления путем рисования его контура To insert a Control by drawing its outline
  21. Использование нескольких элементов управления в ячейках не допускается Multiple Controls Within Cells Are Not Permitted
  22. Демонстрация того, что несколько элементов управления в ячейках не разрешены To demonstrate that multiple controls within cells are not permitted
  23. Переключение элементов управления Swapping Controls
  24. Переключение элементов управления To swap controls
  25. Next Steps Next Steps

Step 4: Lay out your form with a TableLayoutPanel control

In this step, you add a TableLayoutPanel control to your form. The TableLayoutPanel helps properly align controls in the form that you’ll add later.

How to lay out your form with a TableLayoutPanel control

On the left side of the Visual Studio IDE, choose the Toolbox tab. (Alternatively, choose View > Toolbox from the menu bar, or press Ctrl+Alt+X.)

Choose the small triangle symbol next to the Containers group to open it, as shown in the following screenshot.


Containers group

You can add controls like buttons, check boxes, and labels to your form. Double-click the TableLayoutPanel control in the Toolbox. (Or, you can drag the control from the toolbox onto the form.) When you do this, the IDE adds a TableLayoutPanel control to your form, as shown in the following screenshot.


TableLayoutPanel control

After you add your TableLayoutPanel, if a window appears inside your form with the title TableLayoutPanel Tasks, choose anywhere inside the form to close it. You’ll learn more about this window later in the tutorial.

Notice how the Toolbox expands to cover your form when you choose its tab, and closes after you choose anywhere outside of it. That’s the Auto Hide feature in the IDE. You can turn it on or off for any of the windows by choosing the pushpin icon in the upper-right corner of the window to toggle Auto Hide and lock it in place. The pushpin icon appears as follows.


Pushpin icon

Be sure the TableLayoutPanel is selected by choosing it. You can verify what control is selected by looking at the drop-down list at the top of the Properties window, as shown in the following screenshot.


Properties window showing TableLayoutPanel control

Choose the Alphabetical button on the toolbar in the Properties window. This sorts the list of properties in the Properties window in alphabetical order, which makes it easier to locate properties in this tutorial.

The control selector is a drop-down list at the top of the Properties window. In this example, it shows that a control called tableLayoutPanel1 is selected. You can select controls either by choosing an area in Windows Forms Designer or by choosing from the control selector.

Now that the TableLayoutPanel is selected, find the Dock property and choose Dock, which should be set to None. Notice that a drop-down arrow appears next to the value. Choose the arrow, and then select the Fill button (the large button in the middle), as shown in the following screenshot.


Properties window with Fill selected

Docking in Visual Studio refers to when a window is attached to another window or area in the IDE. For example, the Properties window can be undocked—that is, unattached and free-floating within Visual Studio—or it can be docked against Solution Explorer.

After you set the TableLayoutPanel Dock property to Fill, notice that the panel fills the entire form. If you resize the form again, the TableLayoutPanel stays docked, and resizes itself to fit.

A TableLayoutPanel works like a table in Microsoft Office Word: It has rows and columns, and an individual cell can span multiple rows and columns. Each cell can hold one control (like a button, a check box, or a label). Your TableLayoutPanel should have a PictureBox control spanning its entire top row, a CheckBox control in its lower-left cell, and four Button controls in its lower-right cell.

Currently, the TableLayoutPanel has two equal-size rows and two equal-size columns. Let’s resize them so the top row and right column are both much bigger. In Windows Forms Designer, select the TableLayoutPanel. In the upper-right corner, there is a small black triangle button, which appears as follows.

Triangle button

This button indicates that the control has tasks that help you set its properties automatically.

Choose the triangle to display the control’s task list, as shown in the following screenshot.


TableLayoutPanel tasks

Choose the Edit Rows and Columns task to display the Column and Row Styles window. Choose Column1, and set its size to 15 percent by being sure the Percent button is selected and entering 15 in the Percent box. (That’s a NumericUpDown control, which you’ll use in a later tutorial.) Choose Column2 and set it to 85 percent. Don’t choose the OK button yet, because the window will close. (But if you do, you can reopen it by using the task list.)


TableLayoutPanel column and row styles

From the Show drop-down list at the top of the Column and Row Styles window, choose Rows. Set Row1 to 90 percent and Row2 to 10 percent.

Choose the OK button. Your TableLayoutPanel should now have a large top row, a small bottom row, a small left column, and a large right column. (You can resize the rows and columns in the TableLayoutPanel by choosing tableLayoutPanel1 in the form and then dragging its row and column borders.)


Form1 (Picture Viewer) with resized TableLayoutPanel

Next steps

To go to the next tutorial step, see Step 5: Add controls to your form.

To return to the previous tutorial step, see Step 3: Set your form properties.

Пошаговое руководство. Упорядочение элементов управления в формах Windows Forms с помощью элемента TableLayoutPanel Walkthrough: Arranging Controls on Windows Forms Using a TableLayoutPanel

В некоторых приложениях требуется форма, макет которой изменяется надлежащим образом при изменении размера формы или содержимого. Some applications require a form with a layout that arranges itself appropriately as the form is resized or as the contents change in size. Если необходим динамический макет и вы не хотите обрабатывать события Layout явно в коде, рассмотрите возможность использования панели макета. When you need a dynamic layout and you do not want to handle Layout events explicitly in your code, consider using a layout panel.

Читайте также:  Куда загрузилось обновление windows 10

Элементы управления FlowLayoutPanel и TableLayoutPanel предоставляют удобные способы упорядочения элементов управления в форме. The FlowLayoutPanel control and the TableLayoutPanel control provide intuitive ways to arrange controls on your form. Они обеспечивают автоматическую настраиваемую возможность управления относительным положением содержащихся в них дочерних элементов управления и предоставляют функции динамического макета во время выполнения и таким образом могут изменять размер и положение дочерних элементов управления по мере измерения размеров родительской формы. Both provide an automatic, configurable ability to control the relative positions of child controls contained within them, and both give you dynamic layout features at run time, so they can resize and reposition child controls as the dimensions of the parent form change. Панели макета могут быть вложенными в других панелях макета, что позволяет реализовывать сложные пользовательские интерфейсы. Layout panels can be nested within layout panels, to enable the realization of sophisticated user interfaces.

Элемент управления FlowLayoutPanel упорядочивает свое содержимое в определенном направлении, горизонтальном или вертикальном. The FlowLayoutPanel arranges its contents in a specific flow direction: horizontal or vertical. Его содержимое может быть перенесено из одной строки в следующую или из одного столбца в следующий. Its contents can be wrapped from one row to the next, or from one column to the next. Кроме того, вместо переноса содержимое может обрезаться. Alternately, its contents can be clipped instead of wrapped. Дополнительные сведения см. в разделе Пошаговое руководство. Упорядочивание элементов управления в Windows Forms с помощью элемента FlowLayoutPanel. For more information, see Walkthrough: Arranging Controls on Windows Forms Using a FlowLayoutPanel.

TableLayoutPanelКомпонент упорядочивает свое содержимое в сетке, предоставляя функциональные возможности, аналогичные HTML-

элементу. The TableLayoutPanel arranges its contents in a grid, providing functionality similar to the HTML
element. TableLayoutPanelЭлемент управления позволяет размещать элементы управления в макете сетки без необходимости точного указания положения каждого отдельного элемента управления. The TableLayoutPanel control allows you to place controls in a grid layout without requiring you to precisely specify the position of each individual control. Его ячейки организованы в строки и столбцы, и они могут быть разного размера. Its cells are arranged in rows and columns, and these can have different sizes. Ячейки можно объединять между строками и столбцами. Cells can be merged across rows and columns. Ячейки могут содержать все, что может содержать форма, и вести себя в других отношениях в качестве контейнеров. Cells can contain anything a form can contain and behave in most other respects as containers.

Этот TableLayoutPanel элемент управления также предоставляет возможность пропорционального изменения размера во время выполнения, поэтому макет может плавно меняться по мере изменения размера формы. The TableLayoutPanel control also provides a proportional resizing capability at run time, so your layout can change smoothly as your form is resized. Это делает TableLayoutPanel элемент управления хорошо подходящим для таких целей, как формы ввода данных и локализованные приложения. This makes the TableLayoutPanel control well suited for purposes such as data-entry forms and localized applications. Дополнительные сведения см. в разделе Пошаговое руководство. Создание формы Windows с изменяемым размером для ввода данных и Пошаговое руководство. Создание локализуемых форм Windows Forms. For more information, see Walkthrough: Creating a Resizable Windows Form for Data Entry and Walkthrough: Creating a Localizable Windows Form.

В общем случае не следует использовать TableLayoutPanel элемент управления в качестве контейнера для всего макета. In general, you should not use a TableLayoutPanel control as a container for the whole layout. Используйте TableLayoutPanel элементы управления, чтобы обеспечить пропорциональные возможности изменения размера для частей макета. Use TableLayoutPanel controls to provide proportional resizing capabilities to parts of the layout.

В данном пошаговом руководстве представлены следующие задачи. Tasks illustrated in this walkthrough include:

Создание проекта Windows Forms Creating a Windows Forms project

Упорядочение элементов управления в строках и столбцах Arranging Controls in Rows and Columns

Установка свойств строк и столбцов Setting Row and Column Properties

Объединение строк и столбцов с помощью элемента управления Spanning Rows and Columns with a Control

Автоматическая обработка перегрузок Automatic Handling of Overflows

Вставка элементов управления двойным щелчком по ним в панели элементов Inserting Controls by Double-clicking Them in the Toolbox

Вставка элемента управления путем рисования его контура Inserting a Control by Drawing Its Outline

Переназначение существующих элементов управления другим родительским элементам Reassigning Existing Controls to a Different Parent

После завершения вы будете понимать роль, которую играют эти важные функции макета. When you are finished, you will have an understanding of the role played by these important layout features.

Создание проекта Creating the Project

Первым шагом является создание проекта и настройка формы. The first step is to create the project and set up the form.

Создание проекта To create the project

Создайте проект приложения Windows с именем «Таблелайаутпанелексампле». Create a Windows Application project called «TableLayoutPanelExample». Дополнительные сведения см. в разделе инструкции. Создание проекта Windows Forms приложения . For more information, see How to: Create a Windows Forms application project .

Выберите форму в конструкторе Windows Forms. Select the form in the Windows Forms Designer.

Упорядочение элементов управления в строках и столбцах Arranging Controls in Rows and Columns

TableLayoutPanelЭлемент управления позволяет легко упорядочивать элементы управления по строкам и столбцам. The TableLayoutPanel control allows you to easily arrange controls into rows and columns.

Размещение элементов управления в строках и столбцах с помощью TableLayoutPanel To arrange controls in rows and columns using a TableLayoutPanel

Перетащите элемент управления TableLayoutPanel из панели элементов в свою форму. Drag a TableLayoutPanel control from the Toolbox onto your form. Обратите внимание, что по умолчанию TableLayoutPanel элемент управления содержит четыре ячейки. Note that, by default, the TableLayoutPanel control has four cells.

Перетащите Button элемент управления из панели элементов в TableLayoutPanel элемент управления и поместите его в одну из ячеек. Drag a Button control from the Toolbox into the TableLayoutPanel control and drop it into one of the cells. Обратите внимание, что Button элемент управления создается в выбранной ячейке. Note that the Button control is created within the cell you selected.

Перетащите еще три Button элемента управления из панели элементов в TableLayoutPanel элемент управления, чтобы каждая ячейка содержала кнопку. Drag three more Button controls from the Toolbox into the TableLayoutPanel control, so that each cell contains a button.

Возьмите вертикальный маркер изменения размера между двумя столбцами и переместите его влево. Grab the vertical sizing handle between the two columns and move it to the left. Обратите внимание, что Button размеры элементов управления в первом столбце изменяются до меньшей ширины, а размер Button элементов управления во втором столбце не изменяется. Note that the Button controls in the first column are resized to a smaller width, while size of the Button controls in the second column is unchanged.

Возьмите вертикальный маркер изменения размера между двумя столбцами и переместите его вправо. Grab the vertical sizing handle between the two columns and move it to the right. Обратите внимание, что Button элементы управления в первом столбце возвращают исходный размер, а Button элементы управления во втором столбце перемещаются вправо. Note that the Button controls in the first column return to their original size, while the Button controls in the second column are moved to the right.

Переместите горизонтальный маркер изменения размера вверх и вниз, чтобы увидеть воздействие на элементы управления на панели. Move the horizontal sizing handle up and down to see the effect on the controls in the panel.

Размещение элементов управления внутри ячеек с помощью закрепления и привязки Positioning Controls Within Cells Using Docking and Anchoring

Поведение привязки дочерних элементов управления в TableLayoutPanel отличается от поведения в других контейнерных элементах управления. The anchoring behavior of child controls in a TableLayoutPanel differs from the behavior in other container controls. Поведение закрепления дочерних элементов управления аналогично поведению других элементов управления контейнера. The docking behavior of child controls is the same as other container controls.

Размещение элементов управления внутри ячеек Positioning controls within cells

Выберите первый Button элемент управления. Select the first Button control. Измените значение его свойства Dock на Fill. Change the value of its Dock property to Fill. Обратите внимание, что Button элемент управления разворачивается для заполнения ячейки. Note that the Button control expands to fill its cell.

Выберите один из других Button элементов управления. Select one of the other Button controls. Измените значение его свойства Anchor на Right. Change the value of its Anchor property to Right. Обратите внимание, что она перемещается таким образом, что правая граница находится ближе к правой границе ячейки. Note that it is moved so that its right border is near the right border of the cell. Расстояние между границами является суммой Button свойства элемента управления Margin и Padding Свойства панели. The distance between the borders is the sum of the Button control’s Margin property and the panel’s Padding property.

Измените значение Button свойства элемента управления Anchor на Right и Left . Change the value of the Button control’s Anchor property to Right and Left. Обратите внимание, что размер элемента управления изменяется по ширине ячейки с Margin Padding учетом значений и. Note that the control is sized to the width of the cell, with the Margin and Padding values taken into account.

Повторите шаги 2 и 3 с помощью Top Bottom стилей и. Repeat steps 2 and 3 with the Top and Bottom styles.

Установка свойств строк и столбцов Setting Row and Column Properties

Можно задать отдельные свойства строк и столбцов с помощью RowStyles ColumnStyles коллекций и. You can set individual properties of rows and columns by using the RowStyles and ColumnStyles collections.

Задание свойств строк и столбцов To set row and column properties

Выберите TableLayoutPanel элемент управления в конструктор Windows Forms. Select the TableLayoutPanel control in the Windows Forms Designer.

В окнах свойств откройте ColumnStyles коллекцию, нажав кнопку с многоточием ( ) рядом с записью Columns . In the Properties windows, open the ColumnStyles collection by clicking the ellipsis ( ) button next to the Columns entry.

Выберите первый столбец и измените значение его SizeType Свойства на AutoSize . Select the first column and change the value of its SizeType property to AutoSize. Чтобы принять изменение, нажмите кнопку ОК. Click OK to accept the change. Обратите внимание, что ширина первого столбца уменьшается в соответствии с Button элементом управления. Note that the width of the first column is reduced to fit the Button control. Также обратите внимание, что ширина столбца не может изменяться. Also note that the width of the column is not resizable.

В окне Свойства откройте ColumnStyles коллекцию и выберите первый столбец. In the Properties window, open the ColumnStyles collection and select the first column. Измените значение его свойства SizeType на Percent. Change the value of its SizeType property to Percent. Чтобы принять изменение, нажмите кнопку ОК. Click OK to accept the change. Измените размер TableLayoutPanel элемента управления на более крупную ширину и обратите внимание, что ширина первого столбца расширяется. Resize the TableLayoutPanel control to a larger width and note that the width of the first column expands. Измените размер TableLayoutPanel элемента управления до меньшей ширины и обратите внимание, что кнопки в первом столбце имеют размер в соответствии с ячейкой. Resize the TableLayoutPanel control to a smaller width and note that the buttons in the first column are sized to fit the cell. Также обратите внимание, что размер столбца можно изменять. Also note that the width of the column is resizable.

В окне Свойства откройте ColumnStyles коллекцию и выберите все перечисленные столбцы. In the Properties window, open the ColumnStyles collection and select all the listed columns. Присвойте каждому SizeType свойству значение Percent . Set the value of every SizeType property to Percent. Чтобы принять изменение, нажмите кнопку ОК. Click OK to accept the change. Повторите с помощью RowStyles коллекции. Repeat with the RowStyles collection.

Извлеките один из угловых маркеров изменения размера и измените ширину и высоту TableLayoutPanel элемента управления. Grab one of the corner resizing handles and resize both the width and height of the TableLayoutPanel control. Обратите внимание, что размер строк и столбцов изменяется по мере TableLayoutPanel изменения размера элемента управления. Note that the rows and columns are resized as the TableLayoutPanel control’s size changes. Также обратите внимание, что размер строк и столбцов можно изменять с помощью маркеров горизонтального и вертикального размера. Also note that the rows and columns are resizable with the horizontal and vertical sizing handles.

Объединение строк и столбцов с помощью элемента управления Spanning Rows and Columns with a Control

TableLayoutPanelЭлемент управления добавляет несколько новых свойств в элементы управления во время разработки. The TableLayoutPanel control adds several new properties to controls at design time. Двумя из этих свойств являются RowSpan и ColumnSpan . Two of these properties are RowSpan and ColumnSpan . Эти свойства можно использовать, чтобы сделать элемент управления более чем одной строкой или столбцом. You can use these properties to make a control span more than one row or column.

Объединение строк и столбцов с помощью элемента управления To span rows and columns with a control

Выберите Button элемент управления в первой строке и первом столбце. Select the Button control in the first row and first column.

В окнах свойств измените значение ColumnSpan Свойства на 2. In the Properties windows, change the value of the ColumnSpan property to 2. Обратите внимание, что Button элемент управления заполняет первый столбец и второй столбец. Note that the Button control fills the first column and the second column. Кроме того, обратите внимание, что для удовлетворения этого изменения была добавлена дополнительная строка. Also note than an extra row has been added to accommodate this change.

Повторите шаг 2 для RowSpan Свойства. Repeat step 2 for the RowSpan property.

Вставка элементов управления двойным щелчком по ним в панели элементов Inserting Controls by Double-clicking Them in the Toolbox

Вы можете заполнять свой элемент управления TableLayoutPanel , дважды щелкая элементы управления в панели элементов. You can populate your TableLayoutPanel control by double-clicking controls in the Toolbox.

Вставка элементов управления двойным щелчком по ним в панели элементов To insert controls by double-clicking in the Toolbox

Перетащите элемент управления TableLayoutPanel из панели элементов в свою форму. Drag a TableLayoutPanel control from the Toolbox onto your form.

Дважды щелкните значок элемента управления Button в панели элементов. Double-click the Button control icon in the Toolbox. Обратите внимание, что в TableLayoutPanel первой ячейке элемента управления появляется новый элемент управления «Кнопка». Note that a new button control appears in the TableLayoutPanel control’s first cell.

Дважды щелкните несколько других элементов управления в панели элементов. Double-click several more controls in the Toolbox. Обратите внимание, что новые элементы управления последовательно появляются в TableLayoutPanel незанятых ячейках элемента управления. Note that the new controls appear successively in the TableLayoutPanel control’s unoccupied cells. Также обратите внимание, что TableLayoutPanel элемент управления разворачивается в соответствии с новыми элементами управления, если открытые ячейки недоступны. Also note that the TableLayoutPanel control expands to accommodate the new controls if no open cells are available.

Автоматическая обработка перегрузок Automatic Handling of Overflows

При вставке элементов управления в TableLayoutPanel элемент управления для новых элементов управления могут закончится пустые ячейки. When you are inserting controls into the TableLayoutPanel control, you may run out of empty cells for your new controls. TableLayoutPanelЭлемент управления обрабатывает эту ситуацию автоматически, увеличивая число ячеек. The TableLayoutPanel control handles this situation automatically by increasing the number of cells.

Наблюдение за автоматической обработкой перегрузок To observe automatic handling of overflows

Если в элементе управления остались пустые ячейки TableLayoutPanel , продолжайте вставлять новые Button элементы управления, пока TableLayoutPanel элемент управления не будет заполнен. If there are still empty cells in the TableLayoutPanel control, continue inserting new Button controls until the TableLayoutPanel control is full.

После TableLayoutPanel заполнения элемента управления дважды щелкните Button значок на панели элементов , чтобы вставить другой Button элемент управления. Once the TableLayoutPanel control is full, double-click the Button icon in the Toolbox to insert another Button control. Обратите внимание, что TableLayoutPanel элемент управления создает новые ячейки для размещения нового элемента управления. Note that the TableLayoutPanel control creates new cells to accommodate the new control. Вставьте еще несколько элементов управления и обратите внимание на поведение изменения размера. Insert a few more controls and observe the resizing behavior.

Измените значение свойства TableLayoutPanel элемента управления GrowStyle на FixedSize. Change the value of the TableLayoutPanel control’s GrowStyle property to FixedSize. Дважды щелкните Button значок в области элементов , чтобы вставить Button элементы управления до TableLayoutPanel заполнения элемента управления. Double-click the Button icon in the Toolbox to insert Button controls until the TableLayoutPanel control is full. Дважды щелкните Button значок на панели элементов еще раз. Double-click the Button icon in the Toolbox again. Обратите внимание, что в конструктор Windows Forms появляется сообщение об ошибке, информирующее о невозможности создания дополнительных строк и столбцов. Note that you receive an error message from the Windows Forms Designer informing you that additional rows and columns cannot be created.

Вставка элемента управления путем рисования его контура Inserting a Control by Drawing Its Outline

Вы можете вставить элемент управления в элемент управления TableLayoutPanel и задать его размер, нарисовав его контур в ячейке. You can insert a control into a TableLayoutPanel control and specify its size by drawing its outline in a cell.

Вставка элемента управления путем рисования его контура To insert a Control by drawing its outline

Перетащите элемент управления TableLayoutPanel из панели элементов в свою форму. Drag a TableLayoutPanel control from the Toolbox onto your form.

В панели элементов щелкните значок элемента управления Button . In the Toolbox, click the Button control icon. Не перетаскивайте его в форму. Do not drag it onto the form.

Наведите указатель мыши на элемент управления TableLayoutPanel . Move the mouse pointer over the TableLayoutPanel control. Обратите внимание, что указатель превратился в перекрестие с прикрепленным значком элемента управления Button . Note that the pointer changes to a crosshair with the Button control icon attached.

Нажмите и удерживайте кнопку мыши. Click and hold the mouse button.

Перемещайте указатель мыши, чтобы нарисовать контур элемента управления Button . Drag the mouse pointer to draw the outline of the Button control. Когда вас устроит размер, отпустите кнопку мыши. When you are satisfied with the size, release the mouse button. Обратите внимание, что Button элемент управления создается в ячейке, в которой был нарисован контур элемента управления. Note that the Button control is created in the cell in which you drew the control’s outline.

Использование нескольких элементов управления в ячейках не допускается Multiple Controls Within Cells Are Not Permitted

TableLayoutPanelЭлемент управления может содержать только один дочерний элемент управления на одну ячейку. The TableLayoutPanel control can contain only one child control per cell.

Демонстрация того, что несколько элементов управления в ячейках не разрешены To demonstrate that multiple controls within cells are not permitted

  • Перетащите Button элемент управления из панели элементов в TableLayoutPanel элемент управления и поместите его в одну из занятых ячеек. Drag a Button control from the Toolbox into the TableLayoutPanel control and drop it into one of the occupied cells. Обратите внимание, что TableLayoutPanel элемент управления не позволяет поместить Button элемент управления в занятую ячейку. Note that the TableLayoutPanel control does not allow you to drop the Button control into the occupied cell.

Переключение элементов управления Swapping Controls

TableLayoutPanelЭлемент управления позволяет менять местами элементы управления, занимающие две разные ячейки. The TableLayoutPanel control enables you to swap the controls occupying two different cells.

Переключение элементов управления To swap controls

  • Перетащите один из Button элементов управления из занятой ячейки и поместите в другую занятую ячейку. Drag one of the Button controls from an occupied cell and drop into onto another occupied cell. Обратите внимание, что два элемента управления перемещаются из одной ячейки в другую. Note that the two controls are moved from one cell into the other.

Next Steps Next Steps

Используя сочетание панелей макета и элементов управления, можно создавать сложные макеты. You can achieve a complex layout using a combination of layout panels and controls. Для лучшего изучения можно предложить следующее: Suggestions for more exploration include:

Попробуйте Button изменить размер одного из элементов управления на больший, и обратите внимание на изменение макета. Try resizing one of the Button controls to a larger size and note the effect on the layout.

Вставьте в элемент управления несколько элементов управления TableLayoutPanel и обратите внимание на то, как вставляются элементы управления. Paste a selection of multiple controls into the TableLayoutPanel control and note how the controls are inserted.

Панели макета могут содержать другие панели макета. Layout panels can contain other layout panels. Попробуйте вставить элемент управления TableLayoutPanel в существующий элемент управления. Experiment with dropping a TableLayoutPanel control into the existing control.

Закрепите элемент управления TableLayoutPanel в родительской форме. Dock the TableLayoutPanel control to the parent form. Измените размер этой формы и обратите внимание, как это отражается на макете. Resize the form and note the effect on the layout.

Читайте также:  Синий экран 0xc00002e3 windows 10
Оцените статью