Windows forms datagridview button

Data Grid View Button Column Класс

Определение

Размещает коллекцию объектов DataGridViewButtonCell. Hosts a collection of DataGridViewButtonCell objects.

Примеры

В следующем примере кода показано, как использовать DataGridViewButtonColumn для выполнения действий с определенными строками. The following code example demonstrates how to use a DataGridViewButtonColumn to perform actions on particular rows. В этом примере DataGridView.CellClick обработчик событий сначала определяет, находится ли щелчок в ячейке кнопки, а затем извлекает бизнес-объект, связанный со строкой. In this example, a DataGridView.CellClick event handler first determines whether a click is on a button cell, then retrieves a business object associated with the row. Этот пример является частью большого примера, доступного в разделе как получить доступ к объектам в раскрывающемся списке Windows Forms DataGridViewComboBoxCell. This example is part of a larger example available in How to: Access Objects in a Windows Forms DataGridViewComboBoxCell Drop-Down List.

Комментарии

DataGridViewButtonColumnКласс является специализированным типом DataGridViewColumn класса, который используется для логического размещения ячеек, реагирующих на простые входные данные пользователя. The DataGridViewButtonColumn class is a specialized type of the DataGridViewColumn class used to logically host cells that respond to simple user input. DataGridViewButtonColumnУ объекта есть связанный объект DataGridViewButtonCell DataGridViewRow , который пересекает его. A DataGridViewButtonColumn has an associated DataGridViewButtonCell in every DataGridViewRow that intersects it. Каждая ячейка предоставляет пользовательский интерфейс, аналогичный Button элементу управления. Each cell supplies a user interface (UI) that is similar to a Button control.

Чтобы отобразить один и тот же текст кнопки для каждой ячейки, задайте UseColumnTextForButtonValue для свойства значение true и задайте Text для свойства нужный текст кнопки. To display the same button text for every cell, set the UseColumnTextForButtonValue property to true and set the Text property to the desired button text.

По умолчанию для этого типа столбца используется режим сортировки NotSortable . The default sort mode for this column type is NotSortable.

Чтобы реагировать на нажатия кнопок пользователя, обрабатывайте DataGridView.CellClick DataGridView.CellContentClick событие или. To respond to user button clicks, handle the DataGridView.CellClick or DataGridView.CellContentClick event. В обработчике событий можно использовать DataGridViewCellEventArgs.ColumnIndex свойство, чтобы определить, произошло ли нажатие кнопки в столбце кнопки. In the event handler, you can use the DataGridViewCellEventArgs.ColumnIndex property to determine whether the click occurred in the button column. Свойство можно использовать DataGridViewCellEventArgs.RowIndex для определения того, произошла ли щелчок в ячейке кнопки, а не в заголовке столбца. You can use the DataGridViewCellEventArgs.RowIndex property to determine whether the click occurred in a button cell and not on the column header.

Когда визуальные стили включены, кнопки в столбце кнопки рисуются с помощью ButtonRenderer , а стили ячеек, заданные с помощью свойств, таких как, DefaultCellStyle не оказывают никакого влияния. When visual styles are enabled, the buttons in a button column are painted using a ButtonRenderer, and cell styles specified through properties such as DefaultCellStyle have no effect.

Читайте также:  Действия с объектами операционной системы windows

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

При наследовании от DataGridViewButtonColumn и добавлении новых свойств в производный класс обязательно Переопределите Clone() метод, чтобы скопировать новые свойства во время операций клонирования. When you derive from DataGridViewButtonColumn 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.

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

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

Свойства

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

(Унаследовано от DataGridViewColumn) CellTemplate

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

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

(Унаследовано от DataGridViewColumn) ContextMenuStrip

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

(Унаследовано от DataGridViewColumn) DataGridView

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

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

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

(Унаследовано от DataGridViewColumn) DefaultCellStyle

Возвращает или задает стиль по умолчанию для ячеек столбца. 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.

(Унаследовано от DataGridViewColumn) DividerWidth

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

(Унаследовано от DataGridViewColumn) FillWeight

Возвращает или задает значение, представляющее ширину столбца, находящегося в режиме заполнения, относительно ширины других столбцов элемента управления, находящихся в этом режиме. 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.

Читайте также:  Tp link tl wn725n driver mac os

(Унаследовано от DataGridViewColumn) FlatStyle

Получает или задает плоский внешний вид для ячеек кнопок в столбце. Gets or sets the flat-style appearance of the button cells in the column.

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

(Унаследовано от DataGridViewColumn) HasDefaultCellStyle

Получает значение, показывающее, было ли установлено свойство 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.

(Унаследовано от DataGridViewColumn) HeaderCellCore

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

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

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

(Унаследовано от DataGridViewColumn) Index

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

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

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

(Унаследовано от DataGridViewColumn) InheritedStyle

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

(Унаследовано от DataGridViewColumn) IsDataBound

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

(Унаследовано от DataGridViewColumn) IsRow

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

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

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

(Унаследовано от DataGridViewColumn) Name

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

(Унаследовано от DataGridViewColumn) ReadOnly

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

(Унаследовано от DataGridViewColumn) Resizable

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

(Унаследовано от DataGridViewColumn) Selected

Получает или задает значение, показывающее, выделен ли диапазон в пользовательском интерфейсе. 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.

(Унаследовано от DataGridViewColumn) SortMode

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

Читайте также:  Как обновить winetricks альт линукс

(Унаследовано от DataGridViewColumn) State

Получает состояние пользовательского интерфейса для элемента. 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) Text

Получает или задает текст, отображаемый на ячейке кнопки по умолчанию. Gets or sets the default text displayed on the button cell.

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

(Унаследовано от DataGridViewColumn) UseColumnTextForButtonValue

Получает или задает значение, указывающее, отображается ли значение свойства Text как текст на кнопках, которые содержат ячейки в данном столбце. Gets or sets a value indicating whether the Text property value is displayed as the button text for cells in this column.

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

(Унаследовано от DataGridViewColumn) Visible

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

(Унаследовано от DataGridViewColumn) Width

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

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

Методы

Создает точную копию этого столбца. Creates an exact copy of this column.

Освобождает все ресурсы, занятые модулем 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.

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

Определяет, равен ли указанный объект текущему объекту. 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.

(Унаследовано от DataGridViewColumn) GetType()

Возвращает объект 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.

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