Tablelayoutpanel windows forms c

Последнее обновление: 31.10.2015

Элемент TableLayoutPanel также переопределяет панель и располагает дочерние элементы управления в виде таблицы, где для каждого
элемента имеется своя ячейка. Если нам хочется поместить в ячейку более одного элемента, то в эту ячейку добавляется другой компонент
TableLayoutPanel, в который затем вкладываются другие элементы.

Чтобы установить нужное число строки столбцов таблицы, мы можем использовать свойства Rows и Columns соответственно. Выбрав один из этих пунктов в
окне Properties (Свойства), нам отобразится следующее окно для настройки столбцов и строк:

Настройка столбцов и строк элемента TableLayoutPanel

В поле Size Type мы можем указать размер столбцов / строк. Нам доступны три возможные варианта:

  • Absolute: задается абсолютный размер для строк или столбцов в пикселях

  • Percent: задается относительный размер в процентах. Если нам надо создать резиновый дизайн формы, чтобы ее строки и столбцы, а также
    элементы управления в ячейках таблицы автоматически масштабировались при изменении размеров формы, то нам нужно использовать именно эту опцию

  • AutoSize: высота строк и ширина столбцов задается автоматически в зависимости от размера самой большой в строке
    или столбце ячейки

Также мы можем комбинировать эти значения, например, один столбец может быть фиксированным с абсолютной шириной, а остальные столбцы могут иметь
ширину в процентах.

В этом диалоговом окне мы также можем добавить или удалить строки и столбцы. В тоже время графический дизайнер в Visual Studio не всегда сразу отображает
изменения в таблице — добавление или удаление строк и столбцов, изменение их размеров, поэтому, если изменений на форме никаких не происходит, надо ее закрыть и потом
открыть заново в графическом дизайнере.

Итак, например, у меня имеется три столбца и три строки размер у которых одинаков — 33.33%. В каждую ячейку таблицы добавлена кнопка, у которой установлено свойство
Dock=Fill.

Если я изменю размеры формы, то автоматически масштабируются и строки и столбцы вместе с заключенными в них кнопками:

TableLayoutPanel в Windows Forms

Что довольно удобно для создания масштабируемых интерфейсов.

В коде динамически мы можем изменять значения столбцов и строк. Причем все столбцы представлены типом ColumnStyle,
а строки — типом RowStyle:

tableLayoutPanel1.RowStyles[0].SizeType = SizeType.Percent;
tableLayoutPanel1.RowStyles[0].Height = 40;

tableLayoutPanel1.ColumnStyles[0].SizeType = SizeType.Absolute;
tableLayoutPanel1.ColumnStyles[0].Width = 50;

Для установки размера в ColumnStyle и RowStyle определено свойство SizeType, которое принимает одно из значений одноименного перечисления
SizeType

Добавление элемента в контейнер TableLayoutPanel имеет свои особенности. Мы можем добавить его как в следующую свободную ячейку или можем явным
образом указать ячейку таблицы:

Button saveButton = new Button();
// добавляем кнопку в следующую свободную ячейку
tableLayoutPanel1.Controls.Add(saveButton);
// добавляем кнопку в ячейку (2,2)
tableLayoutPanel1.Controls.Add(saveButton, 2, 2);

В данном случае добавляем кнопку в ячейку, образуемую на пересечении третьего столбца и третьей строки. Правда, если у нас нет столько строк и столбцов, то
система автоматически выберет нужную ячейку для добавления.

В некоторых приложениях требуется форма, макет которой изменяется надлежащим образом при изменении размера формы или содержимого. Если необходим динамический макет и вы не хотите обрабатывать события Layout явно в коде, рассмотрите возможность использования панели макета.

Элементы управления FlowLayoutPanel и TableLayoutPanel предоставляют удобные способы упорядочения элементов управления в форме. Они обеспечивают автоматическую настраиваемую возможность управления относительным положением содержащихся в них дочерних элементов управления и предоставляют функции динамического макета во время выполнения и таким образом могут изменять размер и положение дочерних элементов управления по мере измерения размеров родительской формы. Панели макета могут быть вложенными в других панелях макета, что позволяет реализовывать сложные пользовательские интерфейсы.

Элемент управления FlowLayoutPanel упорядочивает свое содержимое в определенном направлении, горизонтальном или вертикальном. Его содержимое может быть перенесено из одной строки в следующую или из одного столбца в следующий. Кроме того, вместо переноса содержимое может обрезаться. Дополнительные сведения см. в разделе Пошаговое руководство: Упорядочение элементов управления в Windows Forms, с помощью элемента FlowLayoutPanel.

TableLayoutPanel Упорядочивает свое содержимое в сетке, обеспечивая функциональные возможности, аналогичные HTML <таблицы > элемента. TableLayoutPanel Элемент управления позволяет размещать элементы управления в виде сетки без необходимости точного указания положения каждого отдельного элемента управления. Его ячейки организованы в строки и столбцы, и они могут быть разного размера. Ячейки могут быть объединены между строками и столбцами. Ячейки могут содержать что-либо формы может содержать и ведут себя во многих отношениях как контейнеры.

TableLayoutPanel Элемент управления также предоставляет возможность пропорционального изменения размера во время выполнения, то макет можно без проблем при изменении размера формы. Это делает TableLayoutPanel управления хорошо подходит для форм ввода данных и локализованных приложений. Дополнительные сведения см. в разделе Пошаговое руководство: Создание переменного размера Windows формы для ввода данных и Пошаговое руководство: Создание формы Windows локализуемые.

В общем случае не следует использовать TableLayoutPanel управления как контейнер для всего макета. Используйте TableLayoutPanel элементы управления для предоставления возможностей пропорционального изменения размера его части.

В данном пошаговом руководстве представлены следующие задачи.

  • Создание проекта Windows Forms

  • Упорядочение элементов управления в строках и столбцах

  • Параметр строки и свойств столбца

  • Объединение строк и столбцов с элементом управления

  • Автоматическая обработка переполнения

  • Вставка элементов управления двойным щелчком по ним в панели элементов

  • Вставка элемента управления путем рисования его контура

  • Переназначение существующих элементов управления другим родительским элементам

После завершения вы будете понимать роль, которую играют эти важные функции макета.

Note

Отображаемые диалоговые окна и команды меню могут отличаться от описанных в справке в зависимости от текущих параметров или выпуска. Чтобы изменить параметры, выберите в меню Сервис пункт Импорт и экспорт параметров . Дополнительные сведения см. в разделе Персонализация интегрированной среды разработки Visual Studio.

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

Первым шагом является создание проекта и настройка формы.

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

  1. Создайте проект приложения Windows с именем «TableLayoutPanelExample». Дополнительные сведения см. в разделе Как Создайте проект приложения Windows Forms .

  2. Выберите форму в Windows конструктора.

Упорядочение элементов управления в строках и столбцах

TableLayoutPanel Элемент управления позволяет легко размещать элементы управления по строкам и столбцам.

Размещение элементов управления в строках и столбцах, с помощью элемента управления TableLayoutPanel

  1. Перетащите элемент управления TableLayoutPanel из панели элементов в свою форму. Обратите внимание, что по умолчанию TableLayoutPanel элемент управления имеет четыре ячейки.

  2. Перетащите Button управления из элементов в TableLayoutPanel управления и поместите его в одну из ячеек. Обратите внимание, что Button создается элемент управления в ячейке, вы выбрали.

  3. Перетащите три дополнительные Button управляет из элементов в TableLayoutPanel таким образом, чтобы каждая ячейка содержит кнопки.

  4. Захватите маркер изменения размера по вертикали между двумя столбцами и переместите его влево. Обратите внимание, что Button элементов управления в первом столбце изменяются уменьшите ширину, а размер Button элементов управления во втором столбце не изменяется.

  5. Захватите маркер изменения размера по вертикали между двумя столбцами и переместите ее вправо. Обратите внимание, что Button элементов управления в первом столбце вернуть их первоначальный размер, тогда как Button перемещении элементов управления во втором столбце справа.

  6. Переместите маркер изменения размера по горизонтали вверх и вниз, чтобы увидеть соответствующий эффект в элементы управления на панели.

Размещение элементов управления внутри ячеек с использованием закрепления и привязки

Функции привязки дочерних элементов управления в TableLayoutPanel отличается от поведения других контейнерных элементов управления. Закрепление дочерних элементов совпадает со значением других контейнерных элементов управления.

Размещение элементов управления в ячейках

  1. Выберите первую Button элемента управления. Измените значение его свойства Dock на Fill. Обратите внимание, что Button управления занимает свою ячейку.

  2. Выберите один из других Button элементов управления. Измените значение его свойства Anchor на Right. Обратите внимание на то, что он перемещается так, чтобы ее правую границу рядом с правой границы ячейки. Расстояние между границами представляет собой сумму Button элемента управления Margin свойство и панели Padding свойство.

  3. Измените значение свойства Button элемента управления Anchor свойства Right и Left. Обратите внимание, что элемент управления имеет размер по ширине ячейки с Margin и Padding значения, взятые в учетную запись.

  4. Повторите шаги 2 и 3 с Top и Bottom стили.

Параметр строки и свойств столбца

Отдельные свойства из строк и столбцов можно задать с помощью RowStyles и ColumnStyles коллекций.

Чтобы задать свойства строк и столбцов

  1. Выберите TableLayoutPanel контролировать конструктор Windows Forms.

  2. В свойства открытых окон ColumnStyles коллекции, нажав кнопку с многоточием () кнопку рядом с полем столбцы запись.

  3. Выберите первый столбец и измените значение его SizeType свойства AutoSize. Нажмите кнопку ОК чтобы принять изменение. Обратите внимание, что ширина первого столбца уменьшается в соответствии с Button элемента управления. Обратите внимание на то, что ширина столбца не является изменяемым размером.

  4. В свойства открытое окно ColumnStyles коллекции и выберите первый столбец. Измените значение его свойства SizeType на Percent. Нажмите кнопку ОК чтобы принять изменение. Изменение размера TableLayoutPanel управления на увеличение ширины и обратите внимание на то, что расширяет ширину первого столбца. Изменение размера TableLayoutPanel управления уменьшите ширину и обратите внимание на то, что кнопки в первом столбце подгоняются под размеры ячейки. Также Обратите внимание, что ширина столбца можно изменять.

  5. В свойства открытое окно ColumnStyles коллекции и выберите все перечисленные столбцы. Установите для параметра каждый SizeType свойства Percent. Нажмите кнопку ОК чтобы принять изменение. Повторите процедуру, используя RowStyles коллекции.

  6. Щелкните один из угловых маркеров изменения размера и изменить ширину и высоту TableLayoutPanel элемента управления. Обратите внимание, что строки и столбцы изменяются как TableLayoutPanel изменения размера элемента управления. Также Обратите внимание, что строк и столбцов можно изменять с горизонтальной и вертикальной маркеры изменения размера.

Объединение строк и столбцов с элементом управления

TableLayoutPanel Управления добавляет несколько новых свойств для элементов управления во время разработки. Два из этих свойств — RowSpan и ColumnSpan. Эти свойства можно использовать, чтобы сделать элемент управления диапазона больше, чем одну строку или столбец.

Чтобы объединение строк и столбцов с элементом управления

  1. Выберите Button элемента управления в первой строке и первом столбце.

  2. В свойства windows, измените значение свойства ColumnSpan свойства 2. Обратите внимание, что Button управления заполняет первый столбец и втором столбце. Обратите внимание на то, чем дополнительную строку был добавлен для реализации этого изменения.

  3. Повторите шаг 2 для RowSpan свойство.

Вы можете заполнять свой элемент управления TableLayoutPanel , дважды щелкая элементы управления в панели элементов.

Вставка элементов управления двойным щелчком по ним в панели элементов

  1. Перетащите элемент управления TableLayoutPanel из панели элементов в свою форму.

  2. Дважды щелкните значок элемента управления Button в панели элементов. Обратите внимание, что отображается новый элемент управления button в TableLayoutPanel первой ячейке элемента управления.

  3. Дважды щелкните несколько других элементов управления в панели элементов. Обратите внимание, что новые элементы управления последовательно появляются в TableLayoutPanel пустых ячейках элемента управления. Также Обратите внимание, что TableLayoutPanel управления расширяется, чтобы вместить новые элементы управления, если доступны открытых ячеек.

Автоматическая обработка переполнения

При вставке элементов управления в TableLayoutPanel элемента управления, вы можете исчерпать пустые ячейки для новых элементов управления. TableLayoutPanel Управления автоматически обрабатывает эту ситуацию, увеличив количество ячеек.

Чтобы наблюдать автоматическую обработку переполнений

  1. Если по-прежнему пустые ячейки в TableLayoutPanel управления, по-прежнему вставки нового Button управляет до TableLayoutPanel заполнения элемента управления.

  2. Один раз TableLayoutPanel заполнения элемента управления, дважды щелкните Button значок в элементов вставляемый другой Button элемента управления. Обратите внимание, что TableLayoutPanel элемент управления создает новые ячейки для размещения нового элемента управления. Вставьте несколько дополнительных элементов управления и наблюдать за поведением изменения размера.

  3. Измените значение свойства TableLayoutPanel элемента управления GrowStyle на FixedSize. Дважды щелкните Button значок в элементов вставляемый Button управляет до TableLayoutPanel заполнения элемента управления. Дважды щелкните Button значок в элементов еще раз. Обратите внимание, что появляется сообщение об ошибке из конструктор Windows Forms информируют о том, что дополнительные строки и столбцы не могут создаваться.

Вставка элемента управления путем рисования его контура

Вы можете вставить элемент управления в элемент управления TableLayoutPanel и задать его размер, нарисовав его контур в ячейке.

Вставка элемента управления путем рисования его контура

  1. Перетащите элемент управления TableLayoutPanel из панели элементов в свою форму.

  2. В панели элементовщелкните значок элемента управления Button . Не перетаскивайте его в форму.

  3. Наведите указатель мыши на элемент управления TableLayoutPanel . Обратите внимание, что указатель превратился в перекрестие с прикрепленным значком элемента управления Button .

  4. Нажмите и удерживайте кнопку мыши.

  5. Перемещайте указатель мыши, чтобы нарисовать контур элемента управления Button . Когда вас устроит размер, отпустите кнопку мыши. Обратите внимание, что Button создается элемент управления в ячейке, в котором нарисован контур элемента управления.

Несколько элементов управления в ячейках не допускаются.

TableLayoutPanel Элемент управления может содержать только один дочерний элемент управления в ячейке.

Чтобы продемонстрировать, что нескольких элементов управления в ячейках не разрешены

  • Перетащите Button управления из элементов в TableLayoutPanel управления и вставьте его в одну из заполненных ячеек. Обратите внимание, что TableLayoutPanel управления не позволяет удалить Button элемента управления в заполненную ячейку.

Перестановки элементов управления

TableLayoutPanel Элемент управления позволяет поменять местами элементы управления, занимающий две разные ячейки.

Для замены элементов управления

  • Перетащите один из Button элементы управления из заполненную ячейку и drop в на другой заполненную ячейку. Обратите внимание на то, что эти два элемента управления перемещаются из одной ячейки в другую.

Следующие шаги

Используя сочетание панелей макета и элементов управления, можно создавать сложные макеты. Рекомендуется также дополнительно исследовать следующие моменты.

  • Попробуйте Button элементы управления для большего размера и Примечание отразится на макете.

  • Вставьте выделение нескольких элементов управления в TableLayoutPanel управления и обратите внимание на то, как вставляются элементы управления.

  • Панели макета могут содержать другие панели макета. Попробуйте вставить элемент управления TableLayoutPanel в существующий элемент управления.

  • Закрепите элемент управления TableLayoutPanel в родительской форме. Измените размер этой формы и обратите внимание, как это отражается на макете.

См. также

  • FlowLayoutPanel
  • TableLayoutPanel
  • Пошаговое руководство. Упорядочение элементов управления в формах Windows Forms с помощью элемента FlowLayoutPanel
  • Пошаговое руководство. Упорядочение элементов управления в формах Windows Forms с помощью линий привязки
  • Взаимодействие с пользователем в Microsoft Windows, официальные рекомендации для разработчиков и конструкторов пользовательских интерфейсов. Редмонд, штат Вашингтон: Microsoft Press, 1999. (USBN: 0-7356-0566-1)
  • Пошаговое руководство. Создание переменного размера Windows формы для ввода данных
  • Пошаговое руководство. Создание формы локализуемые Windows
  • Советы по использованию элемента управления TableLayoutPanel
  • Свойство AutoSize
  • Практическое руководство. Закрепление элементов управления в формах Windows Forms
  • Практическое руководство. Привязка элементов управления в формах Windows Forms
  • Пошаговое руководство. Создание структуры элементов управления Windows Forms с помощью свойств Padding, Margins и AutoSize

<< Back to C-SHARP

Use the TableLayoutPanel control to position controls in a grid format.

TableLayoutPanel positions controls. We require an attractive and functional GUI that resizes properly when users change the size of the window.

First, to make a TableLayoutPanel, expand the toolbox on the left side. Double click on the TableLayoutPanel icon in the left, and then open the Properties pane on the right.

Four-pane panel. You should see a four-pane panel. You will need to modify the number of columns and rows. And then you can change row spans and column spans.

Properties. Anchor is used to align, expand, or fill a control. Column is used to specify number of columns. Row specifies number of rows—add one to get a new row on the bottom.

Anchor. When you click on the space next to Anchor in the Property pane on the right, you will see a box that looks like a +. Click on the rectangles to anchor to that edge.

TextBox. To create a multi-line TextBox that fills the entire cell, set the TextBox as multiline. Add Top and Bottom in the Anchor menu by clicking on the up and down parts of the +.TextBox

Solving layout problems. TableLayoutPanel may solve many of the control alignment problems you have. TableLayoutPanel is flexible and can greatly enhance interfaces.

However, it requires a planning step before dragging controls to your form. TableLayoutPanel is easier to maintain. This planning step is worth taking.

A rigid layout makes life hard for you, as the designer, and the user who is trying to use the program in a slightly different configuration. TableLayoutPanel eliminates these problems.

Related Links:

  • C# Array Examples, String Arrays
  • C# ArrayList Examples
  • C# ArraySegment: Get Array Range, Offset and Count
  • C# break Statement
  • C# Buffer BlockCopy Example
  • C# BufferedStream: Optimize Read and Write
  • 404 Not Found
  • C# 24 Hour Time Formats
  • C# 2D Array Examples
  • 7 Zip Command Line Examples
  • C# 7 Zip Executable (Process.Start)
  • C# All Method: All Elements Match a Condition
  • C# Alphabetize String
  • C# Alphanumeric Sorting
  • C# Arithmetic Expression Optimization
  • C# Array.AsReadOnly Method (ObjectModel)
  • C# Array.BinarySearch Method
  • C# Array.Clear Examples
  • C# Array.IndexOf, LastIndexOf: Search Arrays
  • C# async, await Examples
  • C# Attribute Examples
  • C# Average Method
  • C# BackgroundWorker
  • C# base Keyword
  • C# String Between, Before, After
  • C# Binary Representation int (Convert, toBase 2)
  • C# BinarySearch List
  • C# bool Array (Memory Usage, One Byte Per Element)
  • C# bool.Parse, TryParse: Convert String to Bool
  • C# bool Type
  • C# Array Length Property, Get Size of Array
  • C# Button Example
  • C# Byte Array: Memory Usage, Read All Bytes
  • C# Byte and sbyte Types
  • C# Capacity for List, Dictionary
  • C# Case Insensitive Dictionary
  • C# case Example (Switch Case)
  • C# Char Array
  • C# Checked and Unchecked Keywords
  • C# CheckedListBox: Windows Forms
  • C# Color Table
  • C# Color Examples: FromKnownColor, FromName
  • C# ColorDialog Example
  • C# Comment: Single Line and Multiline
  • C# Concat Extension: Combine Lists and Arrays
  • C# Conditional Attribute
  • C# Console Color, Text and BackgroundColor
  • C# String Clone() method
  • C# Constructor Examples
  • C# Contains Extension Method
  • C# String GetTypeCode() method
  • C# String ToLowerInvariant() method
  • C# Customized Dialog Box
  • C# DataColumn Example: Columns.Add
  • C# DataGridView Add Rows
  • DataGridView Columns, Edit Columns Dialog
  • C# DataGridView Row Colors (Alternating)
  • C# DataGridView Tutorial
  • C# DataGridView
  • C# DataRow Examples
  • C# DataSet Examples
  • C# DataSource Example
  • C# DataTable Compare Rows
  • C# DataTable foreach Loop
  • C# DataTable RowChanged Example: AcceptChanges
  • C# DataTable Select Example
  • C# DataTable Examples
  • C# DataView Examples
  • C# String ToString() method
  • C# String ToUpper() method
  • C# Digit Separator
  • C# DateTime.MinValue (Null DateTime)
  • C# DateTime.Month Property
  • C# DateTime.Parse: Convert String to DateTime
  • C# DateTime Subtract Method
  • C# Decompress GZIP
  • C# Remove Duplicates From List
  • C# dynamic Keyword
  • C# ElementAt, ElementAtOrDefault Use
  • C# Encapsulate Field
  • C# Enum Array Example, Use Enum as Array Index
  • C# enum Flags Attribute Examples
  • C# Enum ToString: Convert Enum to String
  • C# enum Examples
  • C# Enumerable.Range, Repeat and Empty
  • C# Environment Type
  • C# EventLog Example
  • C# Exception Handling
  • C# explicit and implicit Keywords
  • C# Factory Design Pattern
  • C# File.Copy Examples
  • C# typeof and nameof Operators
  • C# String TrimEnd() method
  • C# var Examples
  • C# virtual Keyword
  • C# void Method, Return No Value
  • C# volatile Example
  • C# WebBrowser Control (Navigate Method)
  • C# WebClient: DownloadData, Headers
  • C# Where Method and Keyword
  • C# String TrimStart() method
  • C# delegate Keyword
  • C# descending, ascending Keywords
  • C# while Loop Examples
  • C# Whitespace Methods: Convert UNIX, Windows Newlines
  • C# XmlReader, Parse XML File
  • C# XmlTextReader
  • C# XmlTextWriter
  • C# XmlWriter, Create XML File
  • C# XOR Operator (Bitwise)
  • C# yield Example
  • C# float Numbers
  • FlowLayoutPanel Control
  • C# Focused Property
  • C# FolderBrowserDialog Control
  • C# Font Type: FontFamily and FontStyle
  • C# FontDialog Example
  • C# for Loop Examples
  • C# foreach Loop Examples
  • ForeColor, BackColor: Windows Forms
  • C# Form: Event Handlers
  • C# Contains String Method
  • C# ContainsValue Method (Value Exists in Dictionary)
  • C# ContextMenuStrip Example
  • C# continue Keyword
  • C# Control: Windows Forms
  • C# Windows Forms Controls
  • C# Convert Char Array to String
  • C# Convert Char to String
  • C# Convert Days to Months
  • C# Convert String to Byte Array
  • C# String Format
  • C# Func Object (Lambda That Returns a Value)
  • C# GC.Collect Examples: CollectionCount, GetTotalMemory
  • C# Path.GetDirectoryName (Remove File From Path)
  • C# goto Examples
  • C# HttpClient Example: System.Net.Http
  • ASP.NET HttpContext Request Property
  • IL Disassembler Tutorial
  • C# Intermediate Language (IL)
  • C# IndexOf Examples
  • C# IndexOfAny Examples
  • C# Initialize Array
  • C# Initialize List
  • C# InitializeComponent Method: Windows Forms
  • C# Inline Optimization
  • C# Dictionary Equals: If Contents Are the Same
  • C# Dictionary Versus List Loop
  • C# Dictionary Order, Use Keys Added Last
  • C# Dictionary Size and Performance
  • C# Dictionary Versus List Lookup Time
  • C# Dictionary Examples
  • C# Get Directory Size (Total Bytes in All Files)
  • C# Directory Type
  • C# Distinct Method, Get Unique Elements Only
  • C# Divide by Powers of Two (Bitwise Shift)
  • C# Divide Numbers (Cast Ints)
  • C# DomainUpDown Control Example
  • C# Double Type: double.MaxValue, double.Parse
  • C# Remove Duplicate Chars
  • C# IEqualityComparer
  • C# If Preprocessing Directive: Elif and Endif
  • C# If Versus Switch Performance
  • C# if Statement
  • C# int.MaxValue, MinValue (Get Lowest Number)
  • C# Program to reverse number
  • C# Int and uint Types
  • C# Integer Append Optimization
  • C# Keywords
  • C# Label Example: Windows Forms
  • C# Lambda Expressions
  • C# LastIndexOf Examples
  • C# Last, LastOrDefault Methods
  • C# Mutex Example (OpenExisting)
  • C# Named Parameters
  • C# Let Keyword (Use Variable in Query Expression)
  • C# Levenshtein Distance
  • C# LinkLabel Example: Windows Forms
  • C# LINQ
  • C# List Add Method, Append Element to List
  • C# List AddRange, InsertRange (Append Array to List)
  • C# List Clear Example
  • C# List Contains Method
  • C# List Remove Examples
  • C# List Examples
  • C# ListBox Tutorial (DataSource, SelectedIndex)
  • C# ListView Tutorial: Windows Forms
  • C# Maze Pathfinding Algorithm
  • C# Memoization
  • C# Memory Usage for Arrays of Objects
  • C# MessageBox.Show Examples
  • C# Method Call Depth Performance
  • C# Method Parameter Performance
  • C# Method Size Optimization
  • C# Multidimensional Array
  • C# MultiMap Class (Dictionary of Lists)
  • C# Optimization
  • C# new Keyword
  • C# NotifyIcon: Windows Forms
  • C# NotImplementedException
  • C# Null Array
  • C# String GetType() method
  • C# Null Coalescing and Null Conditional Operators
  • C# Null List (NullReferenceException)
  • C# Numeric Casts
  • C# NumericUpDown Control: Windows Forms
  • C# object.ReferenceEquals Method
  • C# Object Examples
  • C# Optional Parameters
  • C# Prime Number
  • C# OrderBy, OrderByDescending Examples
  • C# Process Examples (Process.Start)
  • Panel, Windows Forms (Create Group of Controls)
  • C# Path Examples
  • C# Get Percentage From Number With Format String
  • ASP.NET PhysicalApplicationPath
  • C# PictureBox: Windows Forms
  • C# PNG Optimization
  • C# Position Windows: Use WorkingArea and Location
  • Visual Studio Post Build, Pre Build Macros
  • C# ProfileOptimization
  • C# ProgressBar Example
  • C# Property Examples
  • C# PropertyGrid: Windows Forms
  • C# Protected and internal Keywords
  • C# Public and private Methods
  • C# Remove Punctuation From String
  • C# Query Windows Forms (Controls.OfType)
  • C# Queryable: IQueryable Interface and AsQueryable
  • ASP.NET QueryString Examples
  • C# Queue Collection: Enqueue
  • C# RadioButton Use: Windows Forms
  • C# ReadOnlyCollection Use (ObjectModel)
  • C# Recursion Optimization
  • C# Recursive File List: GetFiles With AllDirectories
  • C# ref Keyword
  • C# Reflection Examples
  • C# Regex.Escape and Unescape Methods
  • C# StringBuilder Examples
  • C# StringComparison and StringComparer
  • C# StringReader Class (Get Parts of Strings)
  • C# String GetEnumerator() method
  • C# String GetHashCode() method
  • C# Regex Versus Loop: Use For Loop Instead of Regex
  • C# Regex.Match Examples: Regular Expressions
  • C# RemoveAll: Use Lambda to Delete From List
  • C# Replace String Examples
  • ASP.NET Response.BinaryWrite
  • ASP.NET Response.Write
  • C# Return Optimization: out Performance
  • C# SaveFileDialog: Use ShowDialog and FileName
  • C# Scraping HTML Links
  • C# sealed Keyword
  • C# Seek File Examples: ReadBytes
  • C# select new Example: LINQ
  • C# Select Method (Use Lambda to Modify Elements)
  • C# Serialize List (Write to File With BinaryFormatter)
  • C# Settings.settings in Visual Studio
  • C# Shuffle Array: KeyValuePair and List
  • C# Single and Double Types
  • C# Single Instance Windows Form
  • C# Snippet Examples
  • C# Sort DateTime List
  • C# Sort List With Lambda, Comparison Method
  • C# Sort Number Strings
  • C# Sort Examples: Arrays and Lists
  • C# SortedDictionary
  • C# SortedList
  • C# SortedSet Examples
  • C# Split String Examples
  • C# String Copy() method
  • C# SplitContainer: Windows Forms
  • C# SqlClient Tutorial: SqlConnection, SqlCommand
  • C# SqlCommand Example: SELECT TOP, ORDER BY
  • C# SqlCommandBuilder Example: GetInsertCommand
  • C# SqlConnection Example: Using, SqlCommand
  • C# SqlDataAdapter Example
  • C# SqlDataReader: GetInt32, GetString
  • C# SqlParameter Example: Constructor, Add
  • C# Stack Collection: Push, Pop
  • C# Static List: Global List Variable
  • C# Static Regex
  • C# Static String
  • C# static Keyword
  • C# StatusStrip Example: Windows Forms
  • C# String Chars (Get Char at Index)
  • C# string.Concat Examples
  • C# String Interpolation Examples
  • C# string.Join Examples
  • C# String Performance, Memory Usage Info
  • C# String Property
  • C# String Slice, Get Substring Between Indexes
  • C# String Switch Examples
  • C# String
  • C# StringBuilder Append Performance
  • C# StringBuilder Cache
  • C# ToBase64String (Data URI Image)
  • C# Struct Versus Class
  • C# struct Examples
  • C# Substring Examples
  • C# Numeric Suffix Examples
  • C# switch Examples
  • C# String IsNormalized() method
  • C# TabControl: Windows Forms
  • TableLayoutPanel: Windows Forms
  • C# Take and TakeWhile Examples
  • C# Task Examples (Task.Run, ContinueWith and Wait)
  • C# Ternary Operator
  • C# Text Property: Windows Forms
  • C# TextBox.AppendText Method
  • C# TextBox Example
  • C# TextChanged Event
  • C# TextFieldParser Examples: Read CSV
  • C# ThreadStart and ParameterizedThreadStart
  • C# throw Keyword Examples
  • C# Timer Examples
  • C# TimeSpan Examples
  • C# TrimEnd and TrimStart
  • C# True and False
  • C# Truncate String
  • C# String ToLower() method
  • C# String ToCharArray() method
  • C# String ToUpperInvariant() method
  • C# String Trim() method
  • C# Assign Variables Optimization
  • C# Array.Resize Examples
  • C# Array.Sort: Keys, Values and Ranges
  • C# Array.Reverse Example
  • C# Array Slice, Get Elements Between Indexes
  • C# Array.TrueForAll: Use Lambda to Test All Elements
  • C# ArrayTypeMismatchException
  • C# as: Cast Examples
  • C# ASCII Table
  • C# ASCII Transformation, Convert Char to Index
  • C# AsEnumerable Method
  • C# AsParallel Example
  • ASP.NET AspLiteral
  • C# BaseStream Property
  • C# Console.Beep Example
  • C# Benchmark
  • C# BinaryReader Example (Use ReadInt32)
  • C# BinaryWriter Type
  • C# BitArray Examples
  • C# BitConverter Examples
  • C# Bitcount Examples
  • C# Bool Methods, Return True and False
  • C# bool Sort Examples (True to False)
  • C# Caesar Cipher
  • C# Cast Extension: System.Linq
  • C# Cast to Int (Convert Double to Int)
  • C# Cast Examples
  • C# catch Examples
  • C# Change Characters in String (ToCharArray, For Loop)
  • C# Char Combine: Get String From Chars
  • C# char.IsDigit (If Char Is Between 0 and 9)
  • C# char.IsLower and IsUpper
  • C# Character Literal (const char)
  • C# Char Lowercase Optimization
  • C# Char Test (If Char in String Equals a Value)
  • C# char.ToLower and ToUpper
  • C# char Examples
  • C# abstract Keyword
  • C# Action Object (Lambda That Returns Void)
  • C# Aggregate: Use Lambda to Accumulate Value
  • C# AggressiveInlining: MethodImpl Attribute
  • C# Anagram Method
  • C# And Bitwise Operator
  • C# Anonymous Function (Delegate With No Name)
  • C# Any Method, Returns True If Match Exists
  • C# StringBuilder Append and AppendLine
  • C# StringBuilder AppendFormat
  • ASP.NET appSettings Example
  • C# ArgumentException: Invalid Arguments
  • C# Array.ConvertAll, Change Type of Elements
  • C# Array.Copy Examples
  • C# Array.CreateInstance Method
  • C# Array and Dictionary Test, Integer Lookups
  • C# Array.Exists Method, Search Arrays
  • C# Array.Find Examples, Search Array With Lambda
  • C# Array.ForEach: Use Lambda on Every Element
  • C# Array Versus List Memory Usage
  • C# Array Property, Return Empty Array
  • C# CharEnumerator
  • C# Chart, Windows Forms (Series and Points)
  • C# CheckBox: Windows Forms
  • C# class Examples
  • C# Clear Dictionary: Remove All Keys
  • C# Clone Examples: ICloneable Interface
  • C# Closest Date (Find Dates Nearest in Time)
  • C# Combine Arrays: List, Array.Copy and Buffer.BlockCopy
  • C# Combine Dictionary Keys
  • C# ComboBox: Windows Forms
  • C# CompareTo Int Method
  • C# Comparison Object, Used With Array.Sort
  • C# Compress Data: GZIP
  • C# Console.Read Method
  • C# Console.ReadKey Example
  • C# Console.ReadLine Example (While Loop)
  • C# Console.SetOut and Console.SetIn
  • C# Console.WindowHeight
  • C# Console.Write, Append With No Newline
  • C# Console.WriteLine (Print)
  • C# const Example
  • C# Constraint Puzzle Solver
  • C# Count Characters in String
  • C# Count, Dictionary (Get Number of Keys)
  • C# Count Letter Frequencies
  • C# Count Extension Method: Use Lambda to Count
  • C# CSV Methods (Parse and Segment)
  • C# DataRow Field Method: Cast DataTable Cell
  • C# Get Day Count Elapsed From DateTime
  • C# DateTime Format
  • C# DateTime.Now (Current Time)
  • C# DateTime.Today (Current Day With Zero Time)
  • C# DateTime.TryParse and TryParseExact
  • C# DateTime Examples
  • C# DateTimePicker Example
  • C# Debug.Write Examples
  • C# Visual Studio Debugging Tutorial
  • C# decimal Examples
  • C# DayOfWeek
  • C# Enum.Format Method (typeof Enum)
  • C# Enum.GetName, GetNames: Get String Array From Enum
  • C# Enum.Parse, TryParse: Convert String to Enum
  • C# Error and Warning Directives
  • C# ErrorProvider Control: Windows Forms
  • C# event Examples
  • C# Get Every Nth Element From List (Modulo)
  • C# Excel Interop Example
  • C# Except (Remove Elements From Collection)
  • C# Extension Method
  • C# extern alias Example
  • C# Convert Feet, Inches
  • C# File.Delete
  • C# File Equals: Compare Files
  • C# File.Exists Method
  • C# try Keyword
  • C# TryGetValue (Get Value From Dictionary)
  • C# Tuple Examples
  • C# Type Class: Returned by typeof, GetType
  • C# TypeInitializationException
  • C# Union: Combine and Remove Duplicate Elements
  • C# Unreachable Code Detected
  • C# Unsafe Keyword: Fixed, Pointers
  • C# Uppercase First Letter
  • C# Uri and UriBuilder Classes
  • C# Using Alias Example
  • C# using Statement: Dispose and IDisposable
  • C# value Keyword
  • C# ValueTuple Examples (System.ValueTuple, ToTuple)
  • C# ValueType Examples
  • C# Variable Initializer for Class Field
  • C# Word Count
  • C# Word Interop: Microsoft.Office.Interop.Word
  • C# XElement Example (XElement.Load, XName)
  • C# Zip Method (Use Lambda on Two Collections)
  • C# File.Move Method, Rename File
  • C# File.Open Examples
  • C# File.ReadAllBytes, Get Byte Array From File
  • C# File.ReadAllLines, Get String Array From File
  • C# File.ReadAllText, Get String From File
  • C# File.ReadLines, Use foreach Over Strings
  • C# File.Replace Method
  • C# FileInfo Length, Get File Size
  • C# FileInfo Examples
  • C# File Handling
  • C# Filename With Date Example (DateTime.Now)
  • C# FileNotFoundException (catch Example)
  • C# FileStream Length, Get Byte Count From File
  • C# FileStream Example, File.Create
  • C# FileSystemWatcher Tutorial (Changed, e.Name)
  • C# finally Keyword
  • C# First Sentence
  • C# FirstOrDefault (Get First Element If It Exists)
  • C# Fisher Yates Shuffle: Generic Method
  • C# fixed Keyword (unsafe)
  • C# Flatten Array (Convert 2D to 1D)
  • C# First Words in String
  • C# First (Get Matching Element With Lambda)
  • C# ContainsKey Method (Key Exists in Dictionary)
  • C# Convert ArrayList to Array (Use ToArray)
  • C# Convert ArrayList to List
  • C# Convert Bool to Int
  • C# Convert Bytes to Megabytes
  • C# Convert Degrees Celsius to Fahrenheit
  • C# Convert Dictionary to List
  • C# Convert Dictionary to String (Write to File)
  • C# Convert List to Array
  • C# Convert List to DataTable (DataGridView)
  • C# Convert List to String
  • C# Convert Miles to Kilometers
  • C# Convert Milliseconds, Seconds, Minutes
  • C# Convert Nanoseconds, Microseconds, Milliseconds
  • C# Convert String Array to String
  • C# Convert TimeSpan to Long
  • C# Convert Types
  • C# Copy Dictionary
  • C# Count Elements in Array and List
  • C# FromOADate and Excel Dates
  • C# Generic Class, Generic Method Examples
  • C# GetEnumerator: While MoveNext, Get Current
  • C# GetHashCode (String Method)
  • C# Thumbnail Image With GetThumbnailImage
  • C# GetType Method
  • C# Global Variable Examples (Public Static Property)
  • ASP.NET Global Variables Example
  • C# Group By Operator: LINQ
  • GroupBox: Windows Forms
  • C# GroupBy Method: LINQ
  • C# GroupJoin Method
  • C# GZipStream Example (DeflateStream)
  • C# HashSet Examples
  • C# Hashtable Examples
  • HelpProvider Control Use
  • C# HTML and XML Handling
  • C# HtmlEncode and HtmlDecode
  • C# HtmlTextWriter Example
  • C# HttpUtility.HtmlEncode Methods
  • C# HybridDictionary
  • C# default Operator
  • C# DefaultIfEmpty Method
  • C# Define and Undef Directives
  • C# Destructor
  • C# DialogResult: Windows Forms
  • C# Dictionary, Read and Write Binary File
  • C# Dictionary Memory
  • C# Dictionary Optimization, Increase Capacity
  • C# Dictionary Optimization, Test With ContainsKey
  • C# DictionaryEntry Example (Hashtable)
  • C# Directives
  • C# Directory.CreateDirectory, Create New Folder
  • C# Directory.GetFiles Example (Get List of Files)
  • C# DivideByZeroException
  • C# DllImport Attribute
  • C# Do While Loop Example
  • C# DriveInfo Examples
  • C# DropDownItems Control
  • C# IComparable Example, CompareTo: Sort Objects
  • C# IDictionary Generic Interface
  • C# IEnumerable Examples
  • C# IList Generic Interface: List and Array
  • C# Image Type
  • C# ImageList Use: Windows Forms
  • C# Increment String That Contains a Number
  • C# Increment, Preincrement and Decrement Ints
  • Dot Net Perls
  • C# Indexer Examples (This Keyword, get and set)
  • C# IndexOutOfRangeException
  • C# Inheritance
  • C# Insert String Examples
  • C# int Array
  • C# Interface Examples
  • C# Interlocked Examples: Add, CompareExchange
  • C# Intersect: Get Common Elements
  • C# InvalidCastException
  • C# InvalidOperationException: Collection Was Modified
  • C# IOException Type: File, Directory Not Found
  • C# IOrderedEnumerable (Query Expression With orderby)
  • C# is: Cast Examples
  • C# IsFixedSize, IsReadOnly and IsSynchronized Arrays
  • C# string.IsNullOrEmpty, IsNullOrWhiteSpace
  • C# IsSorted Method: If Array Is Already Sorted
  • C# Jagged Array Examples
  • C# join Examples (LINQ)
  • C# KeyCode Property and KeyDown
  • C# KeyNotFoundException: Key Not Present in Dictionary
  • C# KeyValuePair Examples
  • C# Line Count for File
  • C# Line Directive
  • C# LinkedList
  • C# List CopyTo (Copy List Elements to Array)
  • C# List Equals (If Elements Are the Same)
  • C# List Find and Exists Examples
  • C# List Insert Performance
  • ASP.NET LiteralControl Example
  • C# Locality Optimizations (Memory Hierarchy)
  • C# lock Keyword
  • C# Long and ulong Types
  • C# Loop Over String Chars: Foreach, For
  • C# Loop Over String Array
  • C# Main args Examples
  • C# Map Example
  • ASP.NET MapPath: Virtual and Physical Paths
  • C# Mask Optimization
  • C# MaskedTextBox Example
  • C# Math.Abs: Absolute Value
  • C# Math.Ceiling Usage
  • C# Math.Floor Method
  • C# Math.Max and Math.Min Examples
  • C# Math.Pow Method, Exponents
  • C# Math.Round Examples: MidpointRounding
  • C# Math Type
  • C# Max and Min: Get Highest or Lowest Element
  • C# MemoryFailPoint and InsufficientMemoryException
  • C# MemoryStream: Use Stream on Byte Array
  • C# MenuStrip: Windows Forms
  • C# Modulo Operator: Get Remainder From Division
  • C# MonthCalendar Control: Windows Forms
  • C# Multiple Return Values
  • C# Multiply Numbers
  • C# namespace Keyword
  • C# NameValueCollection Usage
  • C# Nested Lists: Create 2D List or Jagged List
  • C# Nested Switch Statement
  • C# Environment.NewLine
  • C# Normalize, IsNormalized Methods
  • C# Null String Example
  • C# null Keyword
  • C# Nullable Examples
  • C# NullReferenceException and Null Parameter
  • C# Object Array
  • C# Obsolete Attribute
  • C# OfType Examples
  • C# OpenFileDialog Example
  • C# operator Keyword
  • C# Odd and Even Numbers
  • C# Bitwise Or
  • C# orderby Query Keyword
  • C# out Parameter
  • C# OutOfMemoryException
  • C# OverflowException
  • C# Overload Method
  • C# Override Method
  • C# PadRight and PadLeft: String Columns
  • C# Get Paragraph From HTML With Regex
  • C# Parallel.For Example (Benchmark)
  • C# Parallel.Invoke: Run Methods on Separate Threads
  • C# Parameter Optimization
  • C# Parameter Passing, ref and out
  • C# params Keyword
  • C# int.Parse: Convert Strings to Integers
  • C# partial Keyword
  • C# Path.ChangeExtension
  • C# Path Exists Example
  • C# Path.GetExtension: File Extension
  • C# Path.GetRandomFileName Method
  • C# Pragma Directive
  • C# Predicate (Lambda That Returns True or False)
  • C# Pretty Date Format (Hours or Minutes Ago)
  • C# PreviewKeyDown Event
  • C# Random Lowercase Letter
  • C# Random Paragraphs and Sentences
  • C# Random String
  • C# Random Number Examples
  • C# StreamReader ReadLine, ReadLineAsync Examples
  • C# readonly Keyword
  • C# Recursion Example
  • C# Regex, Read and Match File Lines
  • C# Regex Groups, Named Group Example
  • C# Regex.Matches Quote Example
  • C# Regex.Matches Method: foreach Match, Capture
  • C# Regex.Replace, Matching End of String
  • C# Regex.Replace, Remove Numbers From String
  • C# Regex.Replace, Merge Multiple Spaces
  • C# Regex.Replace Examples: MatchEvaluator
  • C# Regex.Split, Get Numbers From String
  • C# Regex.Split Examples
  • C# Regex Trim, Remove Start and End Spaces
  • C# RegexOptions.Compiled
  • C# RegexOptions.IgnoreCase Example
  • C# RegexOptions.Multiline
  • C# Region and endregion
  • C# Remove Char From String at Index
  • C# Remove Element
  • C# Remove HTML Tags
  • C# Remove String
  • C# Reserved Filenames
  • C# return Keyword
  • C# Reverse String
  • C# Reverse Words
  • C# Reverse Extension Method
  • C# RichTextBox Example
  • C# Right String Part
  • C# RNGCryptoServiceProvider Example
  • C# ROT13 Method, Char Lookup Table
  • C# SelectMany Example: LINQ
  • C# Sentinel Optimization
  • C# SequenceEqual Method (If Two Arrays Are Equal)
  • C# Shift Operators (Bitwise)
  • C# Short and ushort Types
  • C# Single Method: Get Element If Only One Matches
  • C# SingleOrDefault
  • C# Singleton Pattern Versus Static Class
  • C# Singleton Class
  • C# sizeof Keyword
  • C# Skip and SkipWhile Examples
  • C# Sleep Method (Pause)
  • C# Sort Dictionary: Keys and Values
  • C# Sort by File Size
  • C# Sort, Ignore Leading Chars
  • C# Sort KeyValuePair List: CompareTo
  • C# Sort Strings by Length
  • C# Thread.SpinWait Example
  • C# Math.Sqrt Method
  • C# stackalloc Operator
  • C# StackOverflowException
  • C# StartsWith and EndsWith String Methods
  • C# Static Array
  • C# Static Dictionary
  • C# Stopwatch Examples
  • C# Stream
  • C# StreamReader ReadToEnd Example (Read Entire File)
  • C# StreamReader ReadToEndAsync Example (Performance)
  • C# StreamReader Examples
  • C# StreamWriter Examples
  • C# String Append (Add Strings)
  • C# String Compare and CompareTo Methods
  • C# String Constructor (new string)
  • C# string.Copy Method
  • C# CopyTo String Method: Put Chars in Array
  • C# Empty String Examples
  • C# String Equals Examples
  • C# String For Loop, Count Spaces in String
  • C# string.Intern and IsInterned
  • C# String IsUpper, IsLower
  • C# String Length Property: Get Character Count
  • C# String Literal: Newline and Quote Examples
  • C# StringBuilder Capacity
  • C# StringBuilder Clear (Set Length to Zero)
  • C# StringBuilder Data Types
  • C# StringBuilder Performance
  • C# StringBuilder Equals (If Chars Are Equal)
  • C# StringBuilder Memory
  • C# StringBuilder ToString: Get String From StringBuilder
  • C# StringWriter Class
  • C# Sum Method: Add up All Numbers
  • C# Switch Char, Test Chars With Cases
  • C# Switch Enum
  • C# System (using System namespace)
  • C# Tag Property: Windows Forms
  • C# TextInfo Examples
  • C# TextReader, Returned by File.OpenText
  • C# TextWriter, Returned by File.CreateText
  • C# this Keyword
  • C# ThreadPool
  • C# Thread Join Method (Join Array of Threads)
  • C# ThreadPool.SetMinThreads Method
  • C# TimeZone Examples
  • C# Get Title From HTML With Regex
  • C# ToArray Extension Method
  • C# ToCharArray: Convert String to Array
  • C# ToDictionary Method
  • C# Token
  • C# ToList Extension Method
  • C# ToLookup Method (Get ILookup)
  • C# ToLower and ToUpper: Uppercase and Lowercase Strings
  • ToolStripContainer Control: Dock, Properties
  • C# ToolTip: Windows Forms
  • C# ToString Integer Optimization
  • C# ToString: Get String From Object
  • C# ToTitleCase Method
  • C# TrackBar: Windows Forms
  • C# Tree and Nodes Example: Directed Acyclic Word Graph
  • C# TreeView Tutorial
  • C# Trim Strings
  • C# Thread Methods
  • C# History
  • C# Features
  • C# Variables
  • C# Data Types
  • C# Operators
  • C# Keywords
  • C# New Features | C# Version Features
  • C# Programs
  • C# Program to swap numbers without third variable
  • C# Program to convert Decimal to Binary
  • C# Program to Convert Number in Characters
  • C# Program to Print Alphabet Triangle
  • C# Program to print Number Triangle
  • C# Program to generate Fibonacci Triangle
  • C# String Compare() method
  • C# String CompareOrdinal() method
  • C# String CompareTo() method
  • C# String Concat() method
  • C# String Contains() method
  • C# String CopyTo() method
  • C# String EndsWith() method
  • C# String Equals() method
  • C# String Format() method
  • C# String IndexOf() method
  • C# String Insert() method
  • C# String Intern(String str) method
  • C# String IsInterned() method
  • C# String Normalize() method
  • C# String IsNullOrEmpty() method
  • C# String IsNullOrWhiteSpace() method
  • C# String Join() method
  • C# String LastIndexOf() method
  • C# String LastIndexOfAny() method
  • C# String PadLeft() method
  • C# String PadRight() method
  • C# Nullable
  • C# String Remove() method
  • C# String Replace() method
  • C# String Split() method
  • C# String StartsWith() method
  • C# String SubString() method
  • C# Partial Types
  • C# Iterators
  • C# Delegate Covariance
  • C# Delegate Inference
  • C# Anonymous Types
  • C# Extension Methods
  • C# Query Expression
  • C# Partial Method
  • C# Implicitly Typed Local Variable
  • C# Object and Collection Initializer
  • C# Auto Implemented Properties
  • C# Dynamic Binding
  • C# Named and Optional Arguments
  • C# Asynchronous Methods
  • C# Caller Info Attributes
  • C# Using Static Directive
  • C# Exception Filters
  • C# Await in Catch Finally Blocks
  • C# Default Values for Getter Only Properties
  • C# Expression Bodied Members
  • C# Null Propagator
  • C# String Interpolation
  • C# nameof operator
  • C# Dictionary Initializer
  • C# Pattern Matching
  • C# Tuples
  • C# Deconstruction
  • C# Local Functions
  • C# Binary Literals
  • C# Ref Returns and Locals
  • C# Expression Bodied Constructors and Finalizers
  • C# Expression Bodied Getters and Setters
  • C# Async Main
  • C# Default Expression

Related Links

Adjectives
Ado
Ai
Android
Angular
Antonyms
Apache
Articles
Asp
Autocad
Automata
Aws
Azure
Basic
Binary
Bitcoin
Blockchain
C
Cassandra
Change
Coa
Computer
Control
Cpp
Create
Creating
C-Sharp
Cyber
Daa
Data
Dbms
Deletion
Devops
Difference
Discrete
Es6
Ethical
Examples
Features
Firebase
Flutter
Fs
Git
Go
Hbase
History
Hive
Hiveql
How
Html
Idioms
Insertion
Installing
Ios
Java
Joomla
Js
Kafka
Kali
Laravel
Logical
Machine
Matlab
Matrix
Mongodb
Mysql
One
Opencv
Oracle
Ordering
Os
Pandas
Php
Pig
Pl
Postgresql
Powershell
Prepositions
Program
Python
React
Ruby
Scala
Selecting
Selenium
Sentence
Seo
Sharepoint
Software
Spellings
Spotting
Spring
Sql
Sqlite
Sqoop
Svn
Swift
Synonyms
Talend
Testng
Types
Uml
Unity
Vbnet
Verbal
Webdriver
What
Wpf

The C# TableLayoutPanel control is a powerful tool for creating flexible and structured layouts in your Windows Forms applications. If you’re familiar with HTML tables, the TableLayoutPanel works in a similar way, allowing you to arrange controls in rows and columns. This makes it ideal for scenarios like:

  • Grid-based data entry forms
  • Calendar or schedule displays
  • Custom dashboard-style layouts

Understanding the TableLayoutPanel

Let’s break down the key concepts:

  • Cells:  The basic building blocks of the TableLayoutPanel. Each cell can hold one control or another container panel.
  • Rows and Columns: Define the structure. Add and customize them to fit your layout needs.
  • AutoSize: Automatically resizes rows or columns based on the content within the cells.
  • RowSpan and ColumnSpan: Allow a control to occupy multiple cells within the grid.
  • GrowStyle: Specifies how the TableLayoutPanel should handle adding new controls once the existing grid is filled (AddRows, AddColumns, or FixedSize).

Building a Sample Application

To illustrate these concepts effectively, let’s build a simple hospital bed allocation system. Our example will have:

  • Three floors of beds, arranged in two rows per floor.
  • Scroll bars to accommodate more beds if needed.
  • Visual indicators for allotted, reserved, and available beds.
  • A simple reservation flow.

Step-by-Step Guide

  1. Project Setup:
    • Create a new Windows Forms Application project in Visual Studio.
    • Add a SplitContainer control to the main form, and position its splitter horizontally.
    • Add a TableLayoutPanel to the top panel of the SplitContainer (Panel1).
    • Set the TableLayoutPanel’s Dock property to Fill.
  2. Document Outline:
    • Use the “Document Outline” window to easily visualize the container hierarchy and rename elements for clarity.
  3. Adding Rows and Columns:
    • Add rows to the TableLayoutPanel. Set their SizeType to AutoSize.
    • Initially, add one column.
  4. Controls and Layout:
    • Place labels, buttons, textboxes, etc., in the bottom panel (Panel2) of the SplitContainer.
    • Set the AutoScroll property to True for both the TableLayoutPanel and Panel1.
  5. Floor Labels:
    • Add labels to the TableLayoutPanel representing floor numbers.
    • Utilize the RowSpan property to make each label span two rows of beds.
  6. Adding Beds (Checkboxes):
    • GrowStyle: Set the TableLayoutPanel’s GrowStyle to FixedSize.
      • Coding: In the form’s Load event handler, use nested loops to create checkboxes for each bed:Set each checkbox’s Dock property to Fill.
      • Hook the CheckStateChanged event to a common handler function.
  7. Event Handlers:
      • Implement a handler (e.g., AllotOrFreeBed) to:Determine the bed and floor based on the checkbox that fired the event.
      • Change the checkbox’s appearance to visually indicate its allocation status.
      • Update a status label.
    • Implement a handler for the Reserve button, using GetControlFromPosition to modify the selected bed’s properties.

Code Example (AllotOrFreeBed):

C#

private void AllotOrFreeBed(object sender, EventArgs e)

{

    Control c = (Control)sender;

    TableLayoutPanelCellPosition position = contTable.GetPositionFromControl(c);

    int floorNumber = (position.Row > 1 && position.Row < 4) ? 2 : (position.Row < 2) ? 3 : 1;

    CheckBox chk = (CheckBox)sender;

    if (chk.Checked) 

    {

        chk.BackColor = Color.Yellow; 

        lblDisplay.Text = $”Bed Number {chk.Text} allocated on Floor {floorNumber}”;

    }

   else 

   {

       // … (reset appearance and update status)

   }

}

Tips and Considerations

  • Planning: Sketch your desired layout before coding.
  • Naming: Use meaningful names for controls and variables to improve code readability.

This is a just a small tip to show a simple way of designing the user interface of Windows Forms for Desktops applications.

  • Download sample, updated with auto resize panel — 53.7 KB

Introduction

Over the years, I have seen many developers designing Windows Forms by just dragging and dropping controls, and then repositioning them to match their requirements. When they need to change anything in the design, or when they add a new control, it becomes a little bit messy.

Here is a small demonstration of the technique I use to design Windows Forms, by using a control called TableLayoutPanel. I know that there are so many other techniques, others might use docking properties and anchors for example, but I also intended for this tip to be a discussion forum, where I can also learn about other techniques.

Background

TableLayoutPanel is a control that «Represents a panel that dynamically lays out its contents in a grid composed of rows and columns» (From MSDN: TableLayoutPanel Class).

Basic Requirement

In this sample, we are required to build a simple manual entry form like the below, with some conditions:

Whatever the size of the form (down to a certain extent), even when the form is maximized, the following should always remain true:

  • The size of the text boxes must remain equal for all text boxes, and they must fill the largest space available
  • The labels must all be left aligned
  • The Grid View must fill all of the remaining space
  • A small refresh button must exist below the Grid, it must always be aligned to the right of the form.

Implementation

First let us create a new Windows Forms Applications Project. Expand the main form, and add a new TableLayoutPanel control by dragging it from the Toolbox menu under the «Containers» section.

Expand the new control till it fills the form, and Modify the Anchor property to attach to the 4 sides: «Top, Right, Bottom, Left». name the control «tblPnlMain«.

Add a new Row to the table panel by clicking the small arrow at the right side of the panel, and then choosing «Add Row».

Now remove the last column by clicking the button «Remove Last Column». After that, in the first row, add another TableLayoutPanel and name it «tblPnlDataEntry«. In this panel, we will be placing our labels, text boxes, save and cancel buttons.

Add two additional columns and two additional rows to this new panel.

Set the Anchor of this panel to take all of the four sides, then expand the panel to fill all of its parent container. Please note that in one cell of the table panel, we can only put one control. That’s why we are putting a table panel to be able to add controls as much as we want.

Add 6 labels to the first and third column of the data entry manual form. Set the Anchor of all of them to be just «Left». Set their text properties as: «First Name, Last Name«, «Mobile Phone«, «Home Phone«, «Billing Addresses» and «Country«. Don’t worry about the design now, we will fix that shortly.

Now, in the 2nd and 4th column of the data entry panel, add 6 text boxes. Set the Anchor to all of them to be «Left and Right». This will allow the text boxes to fill the whole width of their parent containers. You will end up with an ugly form like the below:

Now, click on the small arrow on the right side of the Data Entry table panel, and choose «Edit Rows and Columns». For Column 1 and Column 3, set the size type to «Autosize«, this will force the columns to take the width of the largest child control. For Column 2 and Column 4, set the size type to «Percent«, and set the value to 50% for each column. This will tell the columns to take 50 % of the remaining space each.

This will fix our form:

Now, in the 4th row, last column, add another table panel, name it «tblPnlButtons«. For this panel, remove the last row, so that it has only two columns. In the first column, add a button and caption it as «Save». In the second column, add another button and caption it as «Cancel». Set the Anchor property for this panel to Right only. Also set the Anchor for both Buttons to «Right». The form will now look like this:

Now back to the Data Entry Table Panel, Click Edit Rows and Columns, choose the «Rows» item in the drop down list, set the first 3 rows to «AutoSize«, and set the 4th row to «Percent«, giving it 100%, this means that the last row will take all of the remaining space.

Now the form should look like this (if the buttons are still small and not appearing in full, try to expand your form a little bit).

Still something is not right, the Save and Cancel Button are too far from each other. Open the «Table Layout Panel Tasks» for the Buttons table panel, and set the size type of the first column to «Percent«, and the value to 100%, for the second column, set the size type to «AutoSize«.

Now the form will look like this:

Add a Grid View to the second row of the main table panel, and add a button to the last row. Set the Anchor of the grid view to all four sides (Top, Right, Bottom, Left), and set the Anchor of the button to Right. Caption the Button as «Refresh».

Open the Table Layout Panel Tasks for the Main table panel, and set the size type of the first row and last row to «AutoSize«, and the size type of the second row to»Percent«, and the value to 100%. Setting the Size percent of the second row to 100% will ensure that the Grid View will take all of the remaining space.

The completed form will look like this:

Now run the form, resize it, and then maximize it. You will see that the controls are always in order. Set the minimum size of the form to a value of your choice, to ensure that the controls have the minimum space they require to remain in order.

Now for example if you set the Form’s «Right to left» property to true, you will notice that all the controls will still be in place, in order, and with the same proportions. This is one example of the benefits of a TableLayoutPanel, it takes a little bit of effort at the beginning, but it will save you a lot of work later on.

Bonus Tip

This is an update to the original post. Suppose your manual entry form needs more data, you need to add a checkbox which will indicate if the person is married or not. If the person is married, 4 entry fields should appear in the control: Spouse name, spouse last name, spouse age and number of children. If the person is not married, these entry fields should disappear, and the controls should resize to fill the empty space. The final design should look like this:

If the user unchecks the checkbox, the form will change to this, notice how the «Save» and «Cancel» buttons will move up to below the «Is Married» checkbox, and the Grid View will expand to fill up the empty space.

To begin, go the data entry table panel and add three more rows:

Expand the table panel to have more space to add the new controls.

Move the buttons table panel to the last row, the form will now look like below:

Now add 5 labels, set their anchors to left only, and caption them as shown below:

Add a checkbox control to the cell adjacent to the «Is Married» label. Set its Anchor to «Left» and set its Text property to empty string. Now add four text boxes next to the four new labels. Set their Anchor property to «Right» and «Left». 

Now this is important: Set the buttons table panel Anchor to «Top» and «Right», and for the Data Entry Panel, there is a property named «AutoSize«. This will specify if the panel will automatically resize to fits its content, set this property to «True». 

Now still in the Data Entry Panel, Open the «Edit Rows and Columns» box from the «TableLayoutPanel Tasks», and set the Size type for the first 6 rows to «Auto Size», and set the Size type for the last row to «Percent», set its value to 100%.

The form will now look like this:

Expand it a little bit, so that the «Save» and «Cancel» buttons are completely visible:

Now double click on the checkbox next to the «Is Married» label and add the below code, this will hide or show all the new labels and text boxes based on whether this checkbox is checked or not. Set the Checked property of the checkbox to true so that it is checked by default when the form runs:

  label8.Visible=label9.Visible=label10.Visible=label11.Visible=checkBox1.Checked;
            textBox7.Visible = textBox8.Visible = textBox9.Visible = 
            textBox10.Visible = checkBox1.Checked;

Now run the form, When expanded, it will look like this:

When you uncheck the «Is Married» checkbox, the form will automatically reposition and resize its controls accordingly:

You can download the updated sample code from the top of the tip, thanks for following up :).

Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Смена версии windows 10 без переустановки
  • Звуковые темы для windows wav
  • Потоковая передача мультимедиа отключается windows 10
  • Установка postgresql windows django
  • Утилита для полного удаления программ windows 10