- Общие сведения об элементе управления DataGridView (Windows Forms) DataGridView Control Overview (Windows Forms)
- в этом разделе In This Section
- Связанные разделы Related Sections
- Элемент управления DataGrid (Windows Forms) DataGrid Control (Windows Forms)
- в этом разделе In This Section
- Справочник Reference
- Связанные разделы Related Sections
- Практическое руководство. Добавление таблиц и столбцов в элемент управления DataGrid в Windows Forms How to: Add Tables and Columns to the Windows Forms DataGrid Control
- Добавление таблицы и столбца в DataGrid программным способом To add a table and column to a DataGrid programmatically
Общие сведения об элементе управления DataGridView (Windows Forms) DataGridView Control Overview (Windows Forms)
Элемент управления DataGridView заменяет элемент управления DataGrid и расширяет его функциональные возможности; однако при необходимости элемент управления DataGrid можно сохранить для обратной совместимости и использования в будущем. The DataGridView control replaces and adds functionality to the DataGrid control; however, the DataGrid control is retained for both backward compatibility and future use, if you choose. Дополнительные сведения см. в разделе Различия элементов управления DataGridView и DataGrid в Windows Forms. For more information, see Differences Between the Windows Forms DataGridView and DataGrid Controls.
С помощью DataGridView элемента управления можно отображать и редактировать табличные данные из различных типов источников данных. With the DataGridView control, you can display and edit tabular data from many different kinds of data sources.
Привязка данных к DataGridView элементу управления проста и интуитивно понятна, и во многих случаях это так же просто, как установка DataSource Свойства. Binding data to the DataGridView control is straightforward and intuitive, and in many cases it is as simple as setting the DataSource property. При привязке к источнику данных, содержащему несколько списков или таблиц, задайте DataMember для свойства строку, указывающую список или таблицу для привязки. When you bind to a data source that contains multiple lists or tables, set the DataMember property to a string that specifies the list or table to bind to.
DataGridViewЭлемент управления поддерживает стандартную модель привязки данных Windows Forms, поэтому она будет привязана к экземплярам классов, описанным в следующем списке: The DataGridView control supports the standard Windows Forms data binding model, so it will bind to instances of classes described in the following list:
Любой класс, реализующий IList интерфейс, в том числе одномерные массивы. Any class that implements the IList interface, including one-dimensional arrays.
Любой класс, реализующий IListSource интерфейс, например DataTable DataSet классы и. Any class that implements the IListSource interface, such as the DataTable and DataSet classes.
Любой класс, реализующий IBindingList интерфейс, например BindingList класс. Any class that implements the IBindingList interface, such as the BindingList class.
Любой класс, реализующий IBindingListView интерфейс, например BindingSource класс. Any class that implements the IBindingListView interface, such as the BindingSource class.
DataGridViewЭлемент управления поддерживает привязку данных к открытым свойствам объектов, возвращаемых этими интерфейсами, или к коллекции свойств, возвращаемой ICustomTypeDescriptor интерфейсом, если они реализованы в возвращаемых объектах. The DataGridView control supports data binding to the public properties of the objects returned by these interfaces or to the properties collection returned by an ICustomTypeDescriptor interface, if implemented on the returned objects.
Как правило, выполняется привязка к 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. Дополнительные сведения см. в разделе компонент BindingSource. For more information, see BindingSource Component.
DataGridViewЭлемент управления можно также использовать в несвязанном режиме без базового хранилища данных. The DataGridView control can also be used in unbound mode, with no underlying data store. Пример кода, в котором используется несвязанный DataGridView элемент управления, см. в разделе Пошаговое руководство. Создание непривязанного элемента управления Windows Forms DataGridView. For a code example that uses an unbound DataGridView control, see Walkthrough: Creating an Unbound Windows Forms DataGridView Control.
DataGridViewЭлемент управления обладает широкими возможностями настройки и расширяем, и предоставляет множество свойств, методов и событий для настройки внешнего вида и поведения. The DataGridView control is highly configurable and extensible, and it provides many properties, methods, and events to customize its appearance and behavior. Если вы хотите, чтобы в приложении Windows Forms отображались табличные данные, рассмотрите возможность использования DataGridView элемента управления перед другими (например, DataGrid ). When you want your Windows Forms application to display tabular data, consider using the DataGridView control before others (for example, DataGrid). Если вы отображаете маленькую сетку значений, доступных только для чтения, или если вы предоставляете пользователю возможность редактировать таблицу с миллионами записей, DataGridView элемент управления предоставит вам легко Программируемое, эффективное решение для памяти. If you are displaying a small grid of read-only values, or if you are enabling a user to edit a table with millions of records, the DataGridView control will provide you with a readily programmable, memory-efficient solution.
в этом разделе In This Section
Технологическая сводка по элементам управления DataGridView DataGridView Control Technology Summary
Обобщает DataGridView Основные понятия элементов управления и использование связанных классов. Summarizes DataGridView control concepts and the use of related classes.
Архитектура элементов управления DataGridView DataGridView Control Architecture
Описывает архитектуру DataGridView элемента управления, объясняя его иерархию типов и структуру наследования. Describes the architecture of the DataGridView control, explaining its type hierarchy and inheritance structure.
Сценарии использования элементов управления DataGridView DataGridView Control Scenarios
Описывает наиболее распространенные сценарии, в которых DataGridView используются элементы управления. Describes the most common scenarios in which DataGridView controls are used.
Примеры кода для элемента управления DataGridView DataGridView Control Code Directory
Содержит ссылки на примеры кода в документации по различным DataGridView задачам. Provides links to code examples in the documentation for various DataGridView tasks. Примеры распределены на категории по типам задач. These examples are categorized by task type.
Связанные разделы Related Sections
Типы столбцов элемента управления DataGridView в Windows Forms Column Types in the Windows Forms DataGridView Control
Описание типов столбцов в элементе управления Windows Forms, DataGridView используемых для вывода сведений и предоставления пользователям возможности изменять или добавлять данные. Discusses the column types in the Windows Forms DataGridView control used to display information and allow users to modify or add information.
Отображение данных с помощью элемента управления DataGridView в Windows Forms 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.
Настройка элементов управления DataGridView в Windows Forms Customizing the Windows Forms DataGridView Control
Разделы, описывающие пользовательскую отрисовку ячеек и строк DataGridView, а также создание производных ячеек, столбцов и типов строк. Provides topics that describe custom painting DataGridView cells and rows, and creating derived cell, column, and row types.
Оптимизация производительности элемента управления DataGridView в Windows Forms 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.
Элемент управления DataGrid (Windows Forms) DataGrid Control (Windows Forms)
Элемент управления DataGridView заменяет элемент управления DataGrid и расширяет его функциональные возможности; однако при необходимости элемент управления DataGrid можно сохранить для обратной совместимости и использования в будущем. The DataGridView control replaces and adds functionality to the DataGrid control; however, the DataGrid control is retained for both backward compatibility and future use, if you choose. Дополнительные сведения см. в разделе Различия элементов управления DataGridView и DataGrid в Windows Forms. For more information, see Differences Between the Windows Forms DataGridView and DataGrid Controls.
DataGrid Элемент управления Windows Forms предоставляет пользовательский интерфейс для ADO.NET наборов данных, отображения табличных данных и включения обновлений в источнике. The Windows Forms DataGrid control provides a user interface to ADO.NET datasets, displaying tabular data and enabling updates to the data source.
Когда элементу управления DataGrid присвоен допустимый источник данных, этот элемент автоматически заполняется и создаются столбцы и строки, исходя из формы данных. When the DataGrid control is set to a valid data source, the control is automatically populated, creating columns and rows based on the shape of the data. Элемент управления DataGrid можно использовать для отображения одной таблицы или иерархических связей между набором таблиц. The DataGrid control can be used to display either a single table or the hierarchical relationships between a set of tables.
в этом разделе In This Section
Общие сведения об элементе управления DataGrid DataGrid Control Overview
Описание основных возможностей элемента управления DataGrid . Describes the basic features of the DataGrid control.
Практическое руководство. Добавление таблиц и столбцов в элемент управления DataGrid в Windows Forms How to: Add Tables and Columns to the Windows Forms DataGrid Control
Описание программного добавления таблиц и столбцов в элемент управления DataGrid . Describes how to add tables and columns to the DataGrid control programmatically.
Практическое руководство. Привязка элемента управления DataGrid в Windows Forms к источнику данных с помощью конструктора How to: Bind the Windows Forms DataGrid Control to a Data Source Using the Designer
Описывает, как привязать набор данных ADO.NET к DataGrid элементу управления с помощью конструктора. Describes how to bind an ADO.NET dataset to the DataGrid control using the designer.
Практическое руководство. Привязка элемента управления DataGrid в Windows Forms к источнику данных How to: Bind the Windows Forms DataGrid Control to a Data Source
Описывает, как привязать набор данных ADO.NET к DataGrid элементу управления. Describes how to bind an ADO.NET dataset to the DataGrid control.
Практическое руководство. Создание списков основных сведений с использованием элемента управления DataGrid в формах Windows Forms с помощью конструктора How to: Create Master-Details Lists with the Windows Forms DataGrid Control Using the Designer
Описание способа отображения двух таблиц, связанных между собой отношением подчинения, в двух отдельных элементах управления DataGrid с помощью конструктора. Describes how to display two tables, tied together with a parent/child relationship, in two separate DataGrid controls using the designer.
Практическое руководство. Создание основных или подробных списков с помощью элемента управления DataGrid в Windows Forms How to: Create Master-Details Lists with the Windows Forms DataGrid Control
Описание способа отображения двух таблиц, связанных между собой отношением подчинения, в двух отдельных элементах управления DataGrid . Describes how to display two tables, tied together with a parent/child relationship, in two separate DataGrid controls.
Практическое руководство. Форматирование элемента управления DataGrid в формах Windows Forms с помощью конструктора How to: Format the Windows Forms DataGrid Control Using the Designer
Описание способов изменения свойств, связанных с внешним видом элемента управления DataGrid с помощью конструктора. Describes how to change the appearance-related properties of the DataGrid control using the designer.
Практическое руководство. Форматирование элемента управления DataGrid в Windows Forms How to: Format the Windows Forms DataGrid Control
Описание способов изменения свойств, связанных с внешним видом элемента управления DataGrid . Describes how to change the appearance-related properties of the DataGrid control.
Сочетания клавиш для элемента управления DataGrid в Windows Forms Keyboard Shortcuts for the Windows Forms DataGrid Control
Список сочетаний клавиш для навигации по элементу управления DataGrid . Lists shortcuts for navigating through the DataGrid control.
Практическое руководство. Обработка щелчка мыши элементом управления DataGrid в Windows Forms How to: Respond to Clicks in the Windows Forms DataGrid Control
Описание способов определения того, какую ячейку пользователь щелкнул в элементе управления DataGrid . Describes how to determine which cell a user has clicked in the DataGrid control.
Практическое руководство. Проверка данных, вводимых с помощью элемента управления DataGrid, в Windows Forms How to: Validate Input with the Windows Forms DataGrid Control
Описание способов проверки входных данных в наборе данных, привязанном к элементу управления DataGrid . Describes how to validate input in the dataset bound to the DataGrid control.
Справочник Reference
DataGrid
Содержит общие сведения о DataGrid классе. Provides an overview of the DataGrid class.
DataSource
Предоставляет сведения об использовании этого свойства для привязки DataGrid элемента управления к данным. Provides details about using this property to bind the DataGrid control to data.
Связанные разделы Related Sections
Привязка данных Windows Forms Windows Forms Data Binding
Ссылки на разделы о привязке данных в Windows Forms. Provides links to topics on data binding in Windows Forms.
Практическое руководство. Добавление таблиц и столбцов в элемент управления DataGrid в Windows Forms How to: Add Tables and Columns to the Windows Forms DataGrid Control
Элемент управления DataGridView заменяет элемент управления DataGrid и расширяет его функциональные возможности; однако при необходимости элемент управления DataGrid можно сохранить для обратной совместимости и использования в будущем. The DataGridView control replaces and adds functionality to the DataGrid control; however, the DataGrid control is retained for both backward compatibility and future use, if you choose. Дополнительные сведения см. в разделе Различия элементов управления DataGridView и DataGrid в Windows Forms. For more information, see Differences Between the Windows Forms DataGridView and DataGrid Controls.
Данные можно отображать в DataGrid элементах управления Windows Forms в таблицах и столбцах, создавая объекты DataGridTableStyle и добавляя их к объекту GridTableStylesCollection , доступ к которому осуществляется через DataGrid свойство TableStyles элемента управления. You can display data in the Windows Forms DataGrid control in tables and columns by creating DataGridTableStyle objects and adding them to the GridTableStylesCollection object, which is accessed through the DataGrid control’s TableStyles property. Каждый стиль таблицы отображает содержимое любой таблицы данных, указанной в свойстве MappingName объекта DataGridTableStyle . Each table style displays the contents of whatever data table is specified in the DataGridTableStyle object’s MappingName property. По умолчанию в стиле таблицы, в котором не указаны стили столбцов, отображаются все столбцы в таблице данных. By default, a table style with no column styles specified will display all the columns within that data table. Можно ограничить список отображаемых столбцов таблицы, добавив объекты DataGridColumnStyle в объект GridColumnStylesCollection , доступ к которому осуществляется через свойство GridColumnStyles каждого объекта DataGridTableStyle . You can restrict which columns from the table appear by adding DataGridColumnStyle objects to the GridColumnStylesCollection object, which is accessed through the GridColumnStyles property of each DataGridTableStyle object.
Добавление таблицы и столбца в DataGrid программным способом To add a table and column to a DataGrid programmatically
Чтобы отобразить данные в таблице, необходимо сначала привязать DataGrid элемент управления к набору данных. In order to display data in the table, you must first bind the DataGrid control to a dataset. Дополнительные сведения см. в разделе руководство. привязка Windows Forms элемента управления DataGrid к источнику данных. For more information, see How to: Bind the Windows Forms DataGrid Control to a Data Source.
При программном указании стилей столбцов всегда создавайте объекты DataGridColumnStyle и добавляйте их в объект GridColumnStylesCollection перед добавлением объектов DataGridTableStyle в объект GridTableStylesCollection . When programmatically specifying column styles, always create DataGridColumnStyle objects and add them to the GridColumnStylesCollection object before adding DataGridTableStyle objects to the GridTableStylesCollection object. При добавлении пустого объекта DataGridTableStyle в коллекцию объекты DataGridColumnStyle создаются автоматически. When you add an empty DataGridTableStyle object to the collection, DataGridColumnStyle objects are automatically generated for you. Следовательно, при попытке добавить новые объекты DataGridColumnStyle с повторяющимися значениями MappingName в объект GridColumnStylesCollection будет создано исключение. Consequently, an exception will be thrown if you try to add new DataGridColumnStyle objects with duplicate MappingName values to the GridColumnStylesCollection object.
Объявите новый стиль таблицы и задайте его имя сопоставления. Declare a new table style and set its mapping name.
Объявите новый стиль столбца и задайте его имя сопоставления и другие свойства. Declare a new column style and set its mapping name and other properties.
Вызовите метод Add объекта GridColumnStylesCollection , чтобы добавить столбец в стиль таблицы. Call the Add method of the GridColumnStylesCollection object to add the column to the table style
Вызовите метод Add объекта GridTableStylesCollection , чтобы добавить стиль таблицы в сетку данных. Call the Add method of the GridTableStylesCollection object to add the table style to the data grid.