Data Grid View Cell Style Класс
Определение
Представляет сведения о форматировании и стиле, применяемые к отдельным ячейкам в элементе управления DataGridView. Represents the formatting and style information applied to individual cells within a DataGridView control.
Примеры
В следующем примере кода показан результат установки свойств для нескольких DataGridViewCellStyle объектов. The following code example demonstrates the effect of setting properties on multiple DataGridViewCellStyle objects. В этом примере задается цвет фона ячеек в, DataGridView задавая BackColor свойство для DefaultCellStyle Свойства. This example sets the background color of cells in the DataGridView by setting the BackColor property on the DefaultCellStyle property. Цвет фона переопределяется для чередующихся строк, так как BackColor свойство задано для AlternatingRowsDefaultCellStyle Свойства. The background color is overridden on alternating rows because the BackColor property is set on the AlternatingRowsDefaultCellStyle property. В этом примере также определяется формат дат в столбце с заданной Last Prepared установкой Format свойства для DefaultCellStyle Свойства столбца. The example also determines the format of dates in the column named Last Prepared by setting the Format property on the column’s DefaultCellStyle property.
Комментарии
DataGridViewCellStyleКласс позволяет совместно использовать сведения о стилях в нескольких DataGridView ячейках, строках, столбцах и заголовках строк или столбцов, избегая требования к памяти для установки свойств стиля в отдельных ячейках. The DataGridViewCellStyle class lets you share style information across multiple DataGridView cells, rows, columns, and row or column headers, avoiding the memory requirements of setting style properties on individual cells. Дополнительные сведения о классах, имеющих свойство типа DataGridViewCellStyle и о том, как они связаны друг с другом, см. в разделе Стили ячеек в элементе управления Windows Forms DataGridView. For more information about classes that have a property of type DataGridViewCellStyle and how they relate to each other, see Cell Styles in the Windows Forms DataGridView Control.
Конструкторы
Инициализирует новый экземпляр класса DataGridViewCellStyle, используя значения свойства по умолчанию. Initializes a new instance of the DataGridViewCellStyle class using default property values.
Инициализирует новый экземпляр класса DataGridViewCellStyle, используя значения свойств указанного стиля DataGridViewCellStyle. Initializes a new instance of the DataGridViewCellStyle class using the property values of the specified DataGridViewCellStyle.
Свойства
Получает или задает значение, показывающее положение содержимого в ячейке DataGridView. Gets or sets a value indicating the position of the cell content within a DataGridView cell.
Получает или задает цвет фона ячейки DataGridView. Gets or sets the background color of a DataGridView cell.
Получает или задает значение, сохраняемое в источнике данных, когда пользователь вводит в ячейку значение null. Gets or sets the value saved to the data source when the user enters a null value into a cell.
Получает или задает шрифт, применимый к текстовому содержимому ячейки DataGridView. Gets or sets the font applied to the textual content of a DataGridView cell.
Получает или задает основной цвет ячейки DataGridView. Gets or sets the foreground color of a DataGridView cell.
Получает или задает строку формата, применимую к текстовому содержимому ячейки DataGridView. Gets or sets the format string applied to the textual content of a DataGridView cell.
Получает или задает объект, используемый для обеспечения форматирования значений ячеек DataGridView в соответствии с языком и региональными параметрами. Gets or sets the object used to provide culture-specific formatting of DataGridView cell values.
Получает значение, показывающее, было ли установлено свойство DataSourceNullValue. Gets a value indicating whether the DataSourceNullValue property has been set.
Получает значение, показывающее, было ли установлено свойство FormatProvider. Gets a value that indicates whether the FormatProvider property has been set.
Получает значение, показывающее, было ли установлено свойство NullValue. Gets a value indicating whether the NullValue property has been set.
Получает или задает отображаемое значение ячейки DataGridView, соответствующее значению ячейки Value или значение null . Gets or sets the DataGridView cell display value corresponding to a cell value of Value or null .
Получает или задает расстояние между краем ячейки DataGridViewCell и ее содержимым. Gets or sets the space between the edge of a DataGridViewCell and its content.
Получает или задает цвет фона, используемый ячейкой DataGridView, когда она выбрана. Gets or sets the background color used by a DataGridView cell when it is selected.
Получает или задает основной цвет, используемый ячейкой DataGridView, когда она выбрана. Gets or sets the foreground color used by a DataGridView cell when it is selected.
Получает или задает объект, содержащий дополнительные данные, которые относятся к DataGridViewCellStyle. Gets or sets an object that contains additional data related to the DataGridViewCellStyle.
Получает или задает значение, показывающее, переносится ли текстовое содержимое ячейки DataGridView на последующие строки или обрезается, когда оно слишком длинное и не помещается на одной строке. Gets or sets a value indicating whether textual content in a DataGridView cell is wrapped to subsequent lines or truncated when it is too long to fit on a single line.
Методы
Применяет заданный объект DataGridViewCellStyle к текущему объекту DataGridViewCellStyle. Applies the specified DataGridViewCellStyle to the current DataGridViewCellStyle.
Создает точную копию данного объекта DataGridViewCellStyle. Creates an exact copy of this DataGridViewCellStyle.
Возвращает значение, указывающее, эквивалентен ли данный экземпляр заданному объекту. Returns a value indicating whether this instance is equivalent to the specified object.
Выступает в качестве хэш-функции для определенного типа. Serves as a hash function for a particular type.
Возвращает объект Type для текущего экземпляра. Gets the Type of the current instance.
Создает неполную копию текущего объекта Object. Creates a shallow copy of the current Object.
Возвращает строковое значение, показывающее текущие параметры свойства объекта DataGridViewCellStyle. Returns a string indicating the current property settings of the DataGridViewCellStyle.
Явные реализации интерфейса
Создает точную копию данного объекта DataGridViewCellStyle. Creates an exact copy of this DataGridViewCellStyle.
DataGridView Control (Windows Forms)
The DataGridView control provides a powerful and flexible way to display data in a tabular format. You can use the DataGridView control to show read-only views of a small amount of data, or you can scale it to show editable views of very large sets of data.
You can extend the DataGridView control in a number of ways to build custom behaviors into your applications. For example, you can programmatically specify your own sorting algorithms, and you can create your own types of cells. You can easily customize the appearance of the DataGridView control by choosing among several properties. Many types of data stores can be used as a data source, or the DataGridView control can operate with no data source bound to it.
The topics in this section describe the concepts and techniques that you can use to build DataGridView features into your applications.
In This Section
DataGridView Control Overview
Provides topics that describe the architecture and core concepts of the Windows Forms DataGridView control.
Default Functionality in the Windows Forms DataGridView Control
Describes the default appearance and behavior of the Windows Forms DataGridView control when it is bound to a data source.
Column Types in the Windows Forms DataGridView Control
Describes the column types in the Windows Forms DataGridView control used to display data and allow users to modify or add data.
Basic Formatting and Styling in the Windows Forms DataGridView Control
Provides topics that describe how to modify the basic appearance of the control and the display formatting of cell data.
Displaying Data in the Windows Forms DataGridView Control
Provides topics that describe how to populate the control with data either manually, or from an external data source.
Resizing Columns and Rows in the Windows Forms DataGridView Control
Provides topics that describe how the size of rows and columns can be adjusted automatically to fit cell content or to fit the available width of the control.
Sorting Data in the Windows Forms DataGridView Control
Provides topics that describe the sorting features in the control.
Data Entry in the Windows Forms DataGridView Control
Provides topics that describe how to change the way users add and modify data in the control.
Selection and Clipboard Use with the Windows Forms DataGridView Control
Provides topics that describe the cell, row, and column selection features in the control.
Programming with Cells, Rows, and Columns in the Windows Forms DataGridView Control
Provides topics that describe how to program with cell, row, and column objects.
Customizing the Windows Forms DataGridView Control
Provides topics that describe custom painting DataGridView cells and rows, and creating derived cell, column, and row types.
Performance Tuning in the Windows Forms DataGridView Control
Provides topics that describe how to use the control efficiently to avoid performance problems when working with large amounts of data.
Default Keyboard and Mouse Handling in the Windows Forms DataGridView Control
Describes how users can interact with the DataGridView control through a keyboard and a mouse.
Differences Between the Windows Forms DataGridView and DataGrid Controls
Describes how the DataGridView control improves upon and replaces the DataGrid control.
Reference
DataGridView
Provides reference documentation for the DataGridView control.
BindingSource
Provides reference documentation for the BindingSource component. The DataGridView control and the BindingSource component are designed to work closely together.
Data Grid View. Data Source Свойство
Определение
Получает или задает источник данных, для которого объект DataGridView отображает данные. Gets or sets the data source that the DataGridView is displaying data for.
Значение свойства
Объект, содержащий данные, отображаемые в объекте DataGridView. The object that contains data for the DataGridView to display.
Исключения
Произошла ошибка в источнике данных, и нет обработчика для события DataError, или обработчик задал для свойства ThrowException значение true . An error occurred in the data source and either there is no handler for the DataError event or the handler has set the ThrowException property to true . Объект исключения обычно можно привести к типу FormatException. The exception object can typically be cast to type FormatException.
Примеры
В следующем примере кода показано, как инициализировать простую привязку к данным DataGridView . The following code example demonstrates how to initialize a simple data-bound DataGridView. Также показано, как задать DataSource свойство. It also demonstrates how to set the DataSource property.
Комментарии
DataGridViewКласс поддерживает стандартную Windows Forms модель привязки данных. The DataGridView class supports the standard Windows Forms data-binding model. Это означает, что источник данных может иметь любой тип, реализующий один из следующих интерфейсов: This means the data source can be of any type that implements one of the following interfaces:
IListИнтерфейс, включая одномерные массивы. The IList interface, including one-dimensional arrays.
IListSourceИнтерфейс, например DataTable DataSet классы и. The IListSource interface, such as the DataTable and DataSet classes.
IBindingListИнтерфейс, например BindingList класс. The IBindingList interface, such as the BindingList class.
IBindingListViewИнтерфейс, например BindingSource класс. The IBindingListView interface, such as the BindingSource class.
Конкретные примеры см. в разделе «пример» и в таблице задач в конце этого раздела. For specific examples, see the Example section and the task table at the end of this section.
Как правило, выполняется привязка к BindingSource компоненту и привязка BindingSource компонента к другому источнику данных или заполнение его бизнес-объектами. Typically, you will bind to a BindingSource component and bind the BindingSource component to another data source or populate it with business objects. BindingSourceКомпонент является предпочтительным источником данных, поскольку он может выполнять привязку к различным источникам данных и может автоматически устранять множество проблем привязки данных. The BindingSource component is the preferred data source because it can bind to a wide variety of data sources and can resolve many data binding issues automatically.
При привязке к источнику данных, содержащему несколько списков или таблиц, необходимо задать DataMember для свойства строку, указывающую список или таблицу для привязки. When binding to a data source that contains multiple lists or tables, you must set the DataMember property to a string that specifies the list or table to bind to. Однако при привязке к BindingSource компоненту, который содержит несколько списков или таблиц, DataMember вместо него можно задать свойство BindingSource компонента. When binding to a BindingSource component that contains multiple lists or tables, however, you can set the DataMember property of the BindingSource component instead.
При привязке к коллекции объектов, а не к данным базы данных, как правило, DataSourceNullValue свойство объекта, возвращаемого DefaultCellStyle свойством, устанавливается в null , а не используется значение по умолчанию DBNull.Value , которое подходит для данных базы данных. When binding to an object collection rather than to database data, you will typically set the DataSourceNullValue property of the object returned by the DefaultCellStyle property to null rather than using the default value of DBNull.Value, which is appropriate for database data.
Дополнительные сведения см. в разделе Отображение данных в элементе управления Windows Forms DataGridView. For more information, see Displaying Data in the Windows Forms DataGridView Control. В следующей таблице приведены прямые ссылки на общие задачи, связанные с этим DataSource свойством. The following table provides direct links to common tasks related to the DataSource property.