Windows forms datagridview columns

Data Grid View. Columns Свойство

Определение

Возвращает коллекцию, содержащую все столбцы элемента управления. Gets a collection that contains all the columns in the control.

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

Объект DataGridViewColumnCollection, содержащий все столбцы в элементе управления DataGridView. The DataGridViewColumnCollection that contains all the columns in the DataGridView control.

Примеры

В следующем примере кода показано, как создать несвязанное свойство DataGridView , задать ColumnHeadersVisible ColumnHeadersDefaultCellStyle свойства, и, а также ColumnCount использовать Rows Свойства и Columns . The following code example demonstrates how to create an unbound DataGridView; set the ColumnHeadersVisible, ColumnHeadersDefaultCellStyle, and ColumnCount properties; and use the Rows and Columns properties. Также показано, как использовать версию AutoResizeColumnHeadersHeight AutoResizeRows методов и для правильного изменения размера заголовков столбцов и строк. It also demonstrates how to use a version of the AutoResizeColumnHeadersHeight and AutoResizeRows methods to properly size the column headers and the rows. Чтобы выполнить этот пример, вставьте следующий код в форму, содержащую DataGridView именованную dataGridView1 и кнопку с именем Button1 , а затем вызовите InitializeDataGridView метод из конструктора формы или Load обработчика событий. To run this example, paste the following code into a form that contains a DataGridView named dataGridView1 and a button named Button1 , and then call the InitializeDataGridView method from the form’s constructor or Load event handler. Убедитесь, что все события соединены с их обработчиками событий. Ensure all events are connected with their event handlers.

Комментарии

Используя DataGridViewColumnCollection свойство, возвращенное этим свойством, можно добавлять столбцы, удалять столбцы и получать количество столбцов, содержащихся в DataGridView элементе управления. By using the DataGridViewColumnCollection returned by this property, you can add columns, remove columns, and obtain a count of the columns contained in the DataGridView control. Для получения дополнительной информации см. DataGridViewColumnCollection. For more information, see DataGridViewColumnCollection.

Data Grid View Column Класс

Определение

Представляет столбец в элементе управления DataGridView. Represents a column in a DataGridView control.

Примеры

В следующем примере кода создается форма Windows с DataGridView набором кнопок и. The following code example creates a Windows Form with a DataGridView and a set of buttons. Каждая метка кнопки описывает операцию, связанную со DataGridViewColumn свойством, например переключение первого и последнего столбца (с помощью DisplayIndex Свойства) или изменение текста заголовка столбца (с помощью HeaderText Свойства). Each button label describes an operation related to a DataGridViewColumn property, such as swapping the first and last column (using the DisplayIndex property) or changing the text of a column header (using the HeaderText property). При нажатии кнопки изменяется связанное свойство объекта DataGridViewColumn . Clicking a button changes the associated property of the DataGridViewColumn.

Комментарии

DataGridViewColumnКласс представляет логический столбец в DataGridView элементе управления. The DataGridViewColumn class represents a logical column in a DataGridView control. Столбцы можно получить через Columns коллекцию элемента управления. You can retrieve columns through the Columns collection of the control.

В отличие от DataGridViewRow , который содержит фактическую коллекцию ячеек в, в DataGridView DataGridViewColumn основном используется для настройки внешнего вида и поведения пользовательского интерфейса столбца, например ширины столбца и стиля ячейки. Unlike a DataGridViewRow, which contains the actual collection of cells in a DataGridView, DataGridViewColumn is used mainly to adjust the appearance and behavior of the column user interface (UI), such as column width and cell style. Дополнительные сведения о стилях ячеек см. в разделе Стили ячеек в элементе управления Windows Forms DataGridView. For more information about cell styles, see Cell Styles in the Windows Forms DataGridView Control.

Читайте также:  Удалить mdm профиль mac os

Типы, производные от, DataGridViewColumn обычно инициализируют CellTemplate свойство новым экземпляром связанного типа, производного от DataGridViewCell класса. Types that derive from DataGridViewColumn typically initialize the CellTemplate property to a new instance of a related type derived from the DataGridViewCell class. Все свойства столбцов, связанные с внешним видом или поведением отдельных ячеек, являются оболочками для соответствующих свойств ячейки шаблона. Any column properties that relate to the appearance or behavior of individual cells are wrappers for the corresponding properties of the template cell. При изменении одного из этих свойств в столбце автоматически изменяется значение шаблона ячейки и для всех ячеек в столбце. Changing one of these properties on the column automatically changes the value on the cell template and on all cells in the column. Чтобы переопределить указанное значение для отдельных ячеек, задайте значения ячеек после установки значения столбца. To override the specified value for individual cells, set the cell values after you set the column value.

Примечания для тех, кто наследует этот метод

При наследовании от DataGridViewColumn и добавлении новых свойств в производный класс обязательно Переопределите Clone() метод, чтобы скопировать новые свойства во время операций клонирования. When you derive from DataGridViewColumn and add new properties to the derived class, be sure to override the Clone() method to copy the new properties during cloning operations. Также следует вызвать метод базового класса, Clone() чтобы свойства базового класса копировались в новую ячейку. You should also call the base class’s Clone() method so that the properties of the base class are copied to the new cell.

Конструкторы

Инициализирует новый экземпляр класса DataGridViewColumn, устанавливая его в состояние по умолчанию. Initializes a new instance of the DataGridViewColumn class to the default state.

Инициализирует новый экземпляр класса DataGridViewColumn, используя существующий объект DataGridViewCell как шаблон. Initializes a new instance of the DataGridViewColumn class using an existing DataGridViewCell as a template.

Свойства

Возвращает или задает режим, в котором автоматически изменяется ширина столбца. Gets or sets the mode by which the column automatically adjusts its width.

Возвращает или задает шаблон, используемый для создания ячеек. Gets or sets the template used to create new cells.

Возвращает тип времени выполнения шаблона ячеек. Gets the run-time type of the cell template.

Возвращает или задает контекстное меню для столбца. Gets or sets the shortcut menu for the column.

Получает элемент управления DataGridView, связанный с данным элементом. Gets the DataGridView control associated with this element.

Читайте также:  Linux настройка как шлюз

(Унаследовано от DataGridViewElement) DataPropertyName

Возвращает или задает имя того свойства данных или столбца базы данных в источнике данных, с которым связан столбец DataGridViewColumn. Gets or sets the name of the data source property or database column to which the DataGridViewColumn is bound.

Возвращает или задает стиль по умолчанию для ячеек столбца. Gets or sets the column’s default cell style.

Получает или задает тип времени выполнения для ячейки заголовка по умолчанию. Gets or sets the run-time type of the default header cell.

(Унаследовано от DataGridViewBand) Displayed

Получает значение, показывающее, отображается ли диапазон на экране в данный момент. Gets a value indicating whether the band is currently displayed onscreen.

(Унаследовано от DataGridViewBand) DisplayIndex

Возвращает или задает расположение столбца относительно столбцов, отображаемых в текущий момент. Gets or sets the display order of the column relative to the currently displayed columns.

Возвращает или задает ширину (в пикселях) разделителя столбца. Gets or sets the width, in pixels, of the column divider.

Возвращает или задает значение, представляющее ширину столбца, находящегося в режиме заполнения, относительно ширины других столбцов элемента управления, находящихся в этом режиме. Gets or sets a value that represents the width of the column when it is in fill mode relative to the widths of other fill-mode columns in the control.

Возвращает или задает значение, указывающее, перемещается ли столбец, когда пользователь выполняет горизонтальную прокрутку элемента управления DataGridView. Gets or sets a value indicating whether a column will move when a user scrolls the DataGridView control horizontally.

Получает значение, показывающее, было ли установлено свойство DefaultCellStyle. Gets a value indicating whether the DefaultCellStyle property has been set.

(Унаследовано от DataGridViewBand) HeaderCell

Возвращает или задает объект DataGridViewColumnHeaderCell, представляющий заголовок столбца. Gets or sets the DataGridViewColumnHeaderCell that represents the column header.

Получает или задает ячейку заголовка объекта DataGridViewBand. Gets or sets the header cell of the DataGridViewBand.

(Унаследовано от DataGridViewBand) HeaderText

Возвращает или задает текст ячейки заголовка столбца. Gets or sets the caption text on the column’s header cell.

Получает относительную позицию диапазона в элементе управления DataGridView. Gets the relative position of the band within the DataGridView control.

(Унаследовано от DataGridViewBand) InheritedAutoSizeMode

Возвращает или задает режим изменения размера, действующий для столбца. Gets the sizing mode in effect for the column.

Возвращает стиль ячейки, применяемый в текущий момент к столбцу. Gets the cell style currently applied to the column.

Возвращает значение, указывающее, связан ли столбец с источником данных. Gets a value indicating whether the column is bound to a data source.

Получает значение, показывающее, представляет ли диапазон строку. Gets a value indicating whether the band represents a row.

(Унаследовано от DataGridViewBand) MinimumWidth

Возвращает или задает наименьшую ширину столбца (в пикселях). Gets or sets the minimum width, in pixels, of the column.

Возвращает или задает имя столбца. Gets or sets the name of the column.

Возвращает или задает значение, указывающее, может ли пользователь изменять ячейки столбца. Gets or sets a value indicating whether the user can edit the column’s cells.

Читайте также:  Lga1155 драйвера windows 10

Возвращает или задает значение, указывающее, возможно ли изменение размера столбца. Gets or sets a value indicating whether the column is resizable.

Получает или задает значение, показывающее, выделен ли диапазон в пользовательском интерфейсе. Gets or sets a value indicating whether the band is in a selected user interface (UI) state.

(Унаследовано от DataGridViewBand) Site

Возвращает или задает подложку столбца. Gets or sets the site of the column.

Возвращает или задает режим сортировки для столбца. Gets or sets the sort mode for the column.

Получает состояние пользовательского интерфейса для элемента. Gets the user interface (UI) state of the element.

(Унаследовано от DataGridViewElement) Tag

Получает или задает объект, содержащий данные, связанные с диапазоном. Gets or sets the object that contains data to associate with the band.

(Унаследовано от DataGridViewBand) ToolTipText

Возвращает или задает текст, используемый для подсказок. Gets or sets the text used for ToolTips.

Возвращает или задает тип данных для значений в ячейках столбца. Gets or sets the data type of the values in the column’s cells.

Возвращает или задает значение, показывающее, видим ли столбец. Gets or sets a value indicating whether the column is visible.

Возвращает или задает текущую ширину столбца. Gets or sets the current width of the column.

Методы

Создает точную копию данного диапазона. Creates an exact copy of this band.

Освобождает все ресурсы, занятые модулем DataGridViewBand. Releases all resources used by the DataGridViewBand.

(Унаследовано от DataGridViewBand) Dispose(Boolean)

Освобождает неуправляемые ресурсы, используемые объектом DataGridViewBand, а при необходимости освобождает также управляемые ресурсы. Releases the unmanaged resources used by the DataGridViewBand and optionally releases the managed resources.

Определяет, равен ли указанный объект текущему объекту. Determines whether the specified object is equal to the current object.

(Унаследовано от Object) GetHashCode()

Служит хэш-функцией по умолчанию. Serves as the default hash function.

(Унаследовано от Object) GetPreferredWidth(DataGridViewAutoSizeColumnMode, Boolean)

Вычисляет оптимальную ширину столбца на основе указанных критериев. Calculates the ideal width of the column based on the specified criteria.

Возвращает объект Type для текущего экземпляра. Gets the Type of the current instance.

(Унаследовано от Object) MemberwiseClone()

Создает неполную копию текущего объекта Object. Creates a shallow copy of the current Object.

(Унаследовано от Object) OnDataGridViewChanged()

Вызывается, когда диапазон связан с другим элементом управления DataGridView. Called when the band is associated with a different DataGridView.

(Унаследовано от DataGridViewBand) RaiseCellClick(DataGridViewCellEventArgs)

Вызывает событие CellClick. Raises the CellClick event.

(Унаследовано от DataGridViewElement) RaiseCellContentClick(DataGridViewCellEventArgs)

Вызывает событие CellContentClick. Raises the CellContentClick event.

(Унаследовано от DataGridViewElement) RaiseCellContentDoubleClick(DataGridViewCellEventArgs)

(Унаследовано от DataGridViewElement) RaiseCellValueChanged(DataGridViewCellEventArgs)

Вызывает событие CellValueChanged. Raises the CellValueChanged event.

(Унаследовано от DataGridViewElement) RaiseDataError(DataGridViewDataErrorEventArgs)

Вызывает событие DataError. Raises the DataError event.

(Унаследовано от DataGridViewElement) RaiseMouseWheel(MouseEventArgs)

Вызывает событие MouseWheel. Raises the MouseWheel event.

(Унаследовано от DataGridViewElement) ToString()

Возвращает строку, описывающую столбец. Gets a string that describes the column.

События

Происходит при удалении объекта DataGridViewColumn. Occurs when the DataGridViewColumn is disposed.

Оцените статью