- Пошаговое руководство. Создание главного и подчиненного представлений данных с использованием двух элементов управления DataGridView в Windows Forms Walkthrough: Creating a Master/Detail Form Using Two Windows Forms DataGridView Controls
- Предварительные требования Prerequisites
- Создание формы Creating the form
- Создание формы «основной/подробности» To create a master/detail form
- Тестирование приложения Testing the Application
- Тестирование формы To test the form
- Next Steps Next Steps
- Data Grid View Column Класс
- Определение
- Примеры
- Комментарии
- Примечания для тех, кто наследует этот метод
- Конструкторы
- Свойства
- Методы
- События
Пошаговое руководство. Создание главного и подчиненного представлений данных с использованием двух элементов управления DataGridView в Windows Forms Walkthrough: Creating a Master/Detail Form Using Two Windows Forms DataGridView Controls
Одним из наиболее распространенных сценариев использования DataGridView элемента управления является форма « основной/подробности », в которой отображается родительская или дочерняя связь между двумя таблицами базы данных. One of the most common scenarios for using the DataGridView control is the master/detail form, in which a parent/child relationship between two database tables is displayed. Выбор строк в главной таблице приводит к обновлению таблицы сведений соответствующими дочерними данными. Selecting rows in the master table causes the detail table to update with the corresponding child data.
Реализовать форму «основной/подробности» легко с помощью взаимодействия между DataGridView элементом управления и BindingSource компонентом. Implementing a master/detail form is easy using the interaction between the DataGridView control and the BindingSource component. В этом пошаговом руководстве будет построена форма с использованием двух DataGridView элементов управления и двух BindingSource компонентов. In this walkthrough, you will build the form using two DataGridView controls and two BindingSource components. В форме будут показаны две связанные таблицы в образце базы данных Northwind SQL Server: Customers и Orders . The form will show two related tables in the Northwind SQL Server sample database: Customers and Orders . По завершении вы получите форму, в которой будут показаны все клиенты в базе данных в главной области, DataGridView а также все заказы выбранного клиента DataGridView . When you are finished, you will have a form that shows all the customers in the database in the master DataGridView and all the orders for the selected customer in the detail DataGridView.
Предварительные требования Prerequisites
Для выполнения данного пошагового руководства требуется: In order to complete this walkthrough, you will need:
- Доступ к серверу с образцом базы данных Northwind SQL Server. Access to a server that has the Northwind SQL Server sample database.
Создание формы Creating the form
Создание формы «основной/подробности» To create a master/detail form
Создайте класс, производный от Form и содержащий два DataGridView элемента управления и два BindingSource компонента. Create a class that derives from Form and contains two DataGridView controls and two BindingSource components. Следующий код обеспечивает базовую инициализацию формы и включает Main метод. The following code provides basic form initialization and includes a Main method. Если вы используете конструктор Visual Studio для создания формы, вместо этого кода можно использовать созданный конструктором код, но обязательно используйте имена, показанные в объявлениях переменных. If you use the Visual Studio designer to create your form, you can use the designer generated code instead of this code, but be sure to use the names shown in the variable declarations here.
Реализуйте метод в определении класса формы для обработки сведений о подключении к базе данных. Implement a method in your form’s class definition for handling the detail of connecting to the database. В этом примере используется GetData метод, который заполняет DataSet объект, добавляет DataRelation объект в набор данных и связывает BindingSource компоненты. This example uses a GetData method that populates a DataSet object, adds a DataRelation object to the data set, and binds the BindingSource components. Убедитесь, что переменной connectionString присвоено значение, соответствующее базе данных. Be sure to set the connectionString variable to a value that is appropriate for your database.
Хранение конфиденциальных сведений (например, пароля) в строке подключения может повлиять на безопасность приложения. Storing sensitive information, such as a password, within the connection string can affect the security of your application. Использование проверки подлинности Windows (также называемой встроенными средствами безопасности) — более безопасный способ управления доступом к базе данных. Using Windows Authentication (also known as integrated security) is a more secure way to control access to a database. Дополнительные сведения см. в разделе Защита сведений о подключении. For more information, see Protecting Connection Information.
Реализуйте обработчик для Load события формы, который привязывает DataGridView элементы управления к BindingSource компонентам и вызывает GetData метод. Implement a handler for your form’s Load event that binds the DataGridView controls to the BindingSource components and calls the GetData method. Следующий пример включает в себя код, который изменяет размер DataGridView столбцов в соответствии с отображаемыми данными. The following example includes code that resizes DataGridView columns to fit the displayed data.
Тестирование приложения Testing the Application
Теперь можно проверить форму, чтобы убедиться, что она ведет себя так, как ожидалось. You can now test the form to make sure it behaves as expected.
Тестирование формы To test the form
Скомпилируйте и запустите приложение. Compile and run the application.
Вы увидите два DataGridView элемента управления: один над другим. You will see two DataGridView controls, one above the other. В верхней части представлены клиенты из таблицы Northwind Customers , а внизу — Orders соответствующий выбранному клиенту. On top are the customers from the Northwind Customers table, and at the bottom are the Orders corresponding to the selected customer. При выборе различных строк в верхней части DataGridView соответственно изменяется содержимое нижнего DataGridView изменения. As you select different rows in the upper DataGridView, the contents of the lower DataGridView change accordingly.
Next Steps Next Steps
Это приложение предоставляет базовое представление о возможностях DataGridView элемента управления. This application gives you a basic understanding of the DataGridView control’s capabilities. Внешний вид и поведение DataGridView элемента управления можно настроить несколькими способами. You can customize the appearance and behavior of the DataGridView control in several ways:
Проверка входных данных пользователя для DataGridView элемента управления. Validate user input to the DataGridView control. Дополнительные сведения см. в разделе Пошаговое руководство. Проверка данных в элементе управления Windows Forms DataGridView. For more information, see Walkthrough: Validating Data in the Windows Forms DataGridView Control.
Обрабатывайте очень большие наборы данных с помощью виртуального режима. Handle very large data sets using virtual mode. Дополнительные сведения см. в разделе Пошаговое руководство. Реализация виртуального режима в элементе управления Windows Forms DataGridView. For more information, see Walkthrough: Implementing Virtual Mode in the Windows Forms DataGridView Control.
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.
Типы, производные от, 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.
(Унаследовано от DataGridViewElement)
Возвращает или задает имя того свойства данных или столбца базы данных в источнике данных, с которым связан столбец 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)
Получает значение, показывающее, отображается ли диапазон на экране в данный момент. Gets a value indicating whether the band is currently displayed onscreen.
(Унаследовано от DataGridViewBand)
Возвращает или задает расположение столбца относительно столбцов, отображаемых в текущий момент. 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)
Возвращает или задает объект DataGridViewColumnHeaderCell, представляющий заголовок столбца. Gets or sets the DataGridViewColumnHeaderCell that represents the column header.
Получает или задает ячейку заголовка объекта DataGridViewBand. Gets or sets the header cell of the DataGridViewBand.
(Унаследовано от DataGridViewBand)
Возвращает или задает текст ячейки заголовка столбца. 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)
Возвращает или задает режим изменения размера, действующий для столбца. 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)
Возвращает или задает наименьшую ширину столбца (в пикселях). 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.
Возвращает или задает значение, указывающее, возможно ли изменение размера столбца. 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)
Возвращает или задает подложку столбца. 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)
Получает или задает объект, содержащий данные, связанные с диапазоном. Gets or sets the object that contains data to associate with the band.
(Унаследовано от DataGridViewBand)
Возвращает или задает текст, используемый для подсказок. 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)
Освобождает неуправляемые ресурсы, используемые объектом 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)
Служит хэш-функцией по умолчанию. Serves as the default hash function.
(Унаследовано от Object)
Вычисляет оптимальную ширину столбца на основе указанных критериев. Calculates the ideal width of the column based on the specified criteria.
Возвращает объект Type для текущего экземпляра. Gets the Type of the current instance.
(Унаследовано от Object)
Создает неполную копию текущего объекта Object. Creates a shallow copy of the current Object.
(Унаследовано от Object)
Вызывается, когда диапазон связан с другим элементом управления DataGridView. Called when the band is associated with a different DataGridView.
(Унаследовано от DataGridViewBand)
Вызывает событие CellClick. Raises the CellClick event.
(Унаследовано от DataGridViewElement)
Вызывает событие CellContentClick. Raises the CellContentClick event.
(Унаследовано от DataGridViewElement)
(Унаследовано от DataGridViewElement)
Вызывает событие CellValueChanged. Raises the CellValueChanged event.
(Унаследовано от DataGridViewElement)
Вызывает событие DataError. Raises the DataError event.
(Унаследовано от DataGridViewElement)
Вызывает событие MouseWheel. Raises the MouseWheel event.
(Унаследовано от DataGridViewElement)
Возвращает строку, описывающую столбец. Gets a string that describes the column.
События
Происходит при удалении объекта DataGridViewColumn. Occurs when the DataGridViewColumn is disposed.