- Привязка данных Windows Forms Windows Forms Data Binding
- в этом разделе In This Section
- Справочник Reference
- Связанные разделы Related Sections
- Data Binding and Windows Forms
- Types of Data Binding
- BindingSource Component
- Common Scenarios That Employ Data Binding
- Привязка элементов управления Windows Forms к данным в Visual Studio Bind Windows Forms controls to data in Visual Studio
- Элементы управления BindingSource и BindingNavigator BindingSource and BindingNavigator controls
- Привязка к данным в элементе управления DataGridView Bind to data in a DataGridView control
- Привязка к данным в отдельных элементах управления Bind to data in individual controls
Привязка данных Windows Forms Windows Forms Data Binding
Привязка данных в Windows Forms дает возможность отображать и изменять информацию из источника данных в элементах управления в форме. Data binding in Windows Forms gives you the means to display and make changes to information from a data source in controls on the form. В Windows Forms можно выполнить привязку не только к традиционным источникам данных, но и к практически к любой структуре, содержащий данные. You can bind to both traditional data sources as well as almost any structure that contains data.
в этом разделе In This Section
Связывание данных и Windows Forms Data Binding and Windows Forms
Общие сведения о привязке данных в Windows Forms. Provides an overview of data binding in Windows Forms.
Источники данных, поддерживаемые Windows Forms Data Sources Supported by Windows Forms
Описывает источники данных, которые можно использовать с Windows Forms. Describes the data sources that can be used with Windows Forms.
Интерфейсы, относящиеся к привязке данных Interfaces Related to Data Binding
Описывает некоторые интерфейсы, используемые для привязки данных Windows Forms. Describes several of the interfaces used with Windows Forms data binding.
Практическое руководство. Навигация по набору данных, отображаемых в форме Windows Forms How to: Navigate Data in Windows Forms
Показано, как перемещаться по элементам в источнике данных. Shows how to navigate through items in a data source.
Получение уведомления об изменении данных, связанных с элементом управления, в Windows Forms Change Notification in Windows Forms Data Binding
Описывает различные типы уведомлений об изменении для привязки данных Windows Forms. Describes different types of change notification for Windows Forms data binding.
Практическое руководство. Реализация интерфейса INotifyPropertyChanged How to: Implement the INotifyPropertyChanged Interface
Показано, как реализовать интерфейс INotifyPropertyChanged. Shows how to implement the INotifyPropertyChanged interface. Этот интерфейс сообщает связанному элементу управления об изменениях свойств бизнес-объекта The interface communicates to a bound control the property changes on a business object
Практическое руководство. Применение шаблона PropertyNameChanged How to: Apply the PropertyNameChanged Pattern
Показывает, как применить шаблон » PropertyName Changed» к свойствам Windows Forms пользовательского элемента управления. Shows how to apply the PropertyName Changed pattern to properties of a Windows Forms user control.
Практическое руководство. Реализация интерфейса ITypedList How to: Implement the ITypedList Interface
Показано, как задействовать обнаружение схемы для связываемого списка путем реализации интерфейса ITypedList. Shows how to enable discovery of the schema for a bindable list by implementing the ITypedList interface.
Практическое руководство. Реализация интерфейса IListSource How to: Implement the IListSource Interface
Показано, как реализовать интерфейс IListSource, чтобы создать связываемый класс, который не реализует IList, но предоставляет список из другого расположения. Shows how to implement the IListSource interface to create a bindable class does not implement IList, but provides a list from another location.
Практическое руководство. Синхронизация элементов управления, связанных с одним источником данных How to: Ensure Multiple Controls Bound to the Same Data Source Remain Synchronized
Показано, как обрабатывать событие BindingComplete для обеспечения синхронизация всех элементов управления, привязанных к источнику данных. Shows how to handle the BindingComplete event to ensure all controls bound to a data source remain synchronized.
Практическое руководство. Правильное позиционирование выделенной строки в дочерней таблице How to: Ensure the Selected Row in a Child Table Remains at the Correct Position
Показано, как обеспечить сохранение позиции выбранной строки дочерней таблицы при изменении поля родительской таблицы. Shows how to ensure the selected row of a child table does not change, when a change is made to a field of the parent table.
Справочник Reference
System.Windows.Forms.Binding
Описывает класс, представляющий связку между связываемым компонентом и источником данных. Describes the class that represents the binding between a bindable component and a data source.
System.Windows.Forms.BindingSource
Описывает класс, инкапсулирующий источник данных для привязки к элементам управления. Describes the class that encapsulates a data source for binding to controls.
Связанные разделы Related Sections
Компонент BindingSource BindingSource Component
Содержит список разделов, описывающих использование компонента BindingSource. Contains a list of topics that demonstrate how to use the BindingSource component.
Элемент управления DataGridView DataGridView Control
Предоставляет список разделов, в которых демонстрируется использование связываемого элемента управления datagrid. Provides a list of topics that demonstrate how to use a bindable datagrid control.
Data Binding and Windows Forms
In Windows Forms, you can bind to not just traditional data sources, but also to almost any structure that contains data. You can bind to an array of values that you calculate at run time, read from a file, or derive from the values of other controls.
In addition, you can bind any property of any control to the data source. In traditional data binding, you typically bind the display property—for example, the Text property of a TextBox control—to the data source. With the .NET Framework, you also have the option of setting other properties through binding as well. You might use binding to perform the following tasks:
Setting the graphic of an image control.
Setting the background color of one or more controls.
Setting the size of controls.
Essentially, data binding is an automatic way of setting any run-time accessible property of any control on a form.
Types of Data Binding
Windows Forms can take advantage of two types of data binding: simple binding and complex binding. Each offers different advantages.
Type of data binding | Description |
---|---|
Simple data binding | The ability of a control to bind to a single data element, such as a value in a column in a dataset table. This is the type of binding typical for controls such as a TextBox control or Label control, which are controls that typically only displays a single value. In fact, any property on a control can be bound to a field in a database. There is extensive support for this feature in Visual Studio. For more information, see: — Interfaces Related to Data Binding |
Complex data binding | The ability of a control to bind to more than one data element, typically more than one record in a database. Complex binding is also called list-based binding. Examples of controls that support complex binding are the DataGridView, ListBox, and ComboBox controls. For an example of complex data binding, see How to: Bind a Windows Forms ComboBox or ListBox Control to Data. |
BindingSource Component
To simplify data binding, Windows Forms enables you to bind a data source to the BindingSource component and then bind controls to the BindingSource. You can use the BindingSource in simple or complex binding scenarios. In either case, the BindingSource acts as an intermediary between the data source and bound controls providing change notification currency management and other services.
Common Scenarios That Employ Data Binding
Nearly every commercial application uses information read from data sources of one type or another, usually through data binding. The following list shows a few of the most common scenarios that utilize data binding as the method of data presentation and manipulation.
Привязка элементов управления Windows Forms к данным в Visual Studio Bind Windows Forms controls to data in Visual Studio
Вы можете отображать данные для пользователей приложения, привязывая данные к Windows Forms. You can display data to users of your application by binding data to Windows Forms. Чтобы создать эти элементы управления с привязкой к данным, перетащите элементы из окна Источники данных на конструктор Windows Forms в Visual Studio. To create these data-bound controls, drag items from the Data Sources window onto the Windows Forms Designer in Visual Studio.
Если окно Источники данных не отображается, его можно открыть, выбрав Просмотреть > другие > Источники данных Windows или нажав клавиши SHIFT + ALT + D. If the Data Sources window is not visible, you can open it by choosing View > Other Windows > Data Sources, or by pressing Shift+Alt+D. Для просмотра окна Источники данных в Visual Studio должен быть открыт проект. You must have a project open in Visual Studio to see the Data Sources window.
Перед перетаскиванием элементов можно задать тип элемента управления, к которому необходимо выполнить привязку. Before you drag items, you can set the type of control you want to bind to. Различные значения отображаются в зависимости от выбора самой таблицы или отдельного столбца. Different values appear depending on whether you choose the table itself, or an individual column. Можно также задать пользовательские значения. You can also set custom values. Для таблицы сведения означает, что каждый столбец привязан к отдельному элементу управления. For a table, Details means that each column is bound to a separate control.
Элементы управления BindingSource и BindingNavigator BindingSource and BindingNavigator controls
Компонент BindingSource служит двум целям. The BindingSource component serves two purposes. Во-первых, он предоставляет уровень абстракции при привязке элементов управления к данным. First, it provides a layer of abstraction when binding the controls to data. Элементы управления в форме привязываются к BindingSource компоненту, а не непосредственно к источнику данных. Controls on the form are bound to the BindingSource component instead of directly to a data source. Во-вторых, он может управлять коллекцией объектов. Second, it can manage a collection of objects. Добавление типа в BindingSource создает список этого типа. Adding a type to the BindingSource creates a list of that type.
Дополнительные сведения о BindingSource компоненте см. в следующих статьях: For more information about the BindingSource component, see:
Элемент управления BindingNavigator предоставляет пользовательский интерфейс для навигации по данным, отображаемым приложением Windows. The BindingNavigator control provides a user interface for navigating through data displayed by a Windows application.
Привязка к данным в элементе управления DataGridView Bind to data in a DataGridView control
Для элемента управления DataGridViewвся таблица привязана к этому отдельному элементу управления. For a DataGridView control, the entire table is bound to that single control. При перетаскивании элемента DataGridView в форму также появляется панель инструментов для навигации по записям ( BindingNavigator ). When you drag a DataGridView to the form, a tool strip for navigating records (BindingNavigator) also appears. Набор данных, TableAdapter, BindingSource и BindingNavigator отображается в области компонентов. A DataSet, TableAdapter, BindingSource, and BindingNavigator appear in the component tray. На следующем рисунке также добавлен TableAdapterManager , так как таблица Customers имеет связь с таблицей Orders. In the following illustration, a TableAdapterManager is also added because the Customers table has a relation to the Orders table. Все эти переменные объявляются в автоматически созданном коде как закрытые члены класса Form. These variables are all declared in the auto-generated code as private members in the form class. Автоматически созданный код для заполнения DataGridView находится в Form_Load обработчике событий. The auto-generated code for filling the DataGridView is located in the Form_Load event handler. Код для сохранения данных для обновления базы данных находится в Save обработчике событий для BindingNavigator. The code for saving the data to update the database is located in the Save event handler for the BindingNavigator. Этот код можно перемещать или изменять при необходимости. You can move or modify this code as needed.
Поведение DataGridView и BindingNavigator можно настроить, щелкнув смарт-тег в правом верхнем углу каждого из них: You can customize the behavior of the DataGridView and the BindingNavigator by clicking on the smart tag in the upper-right corner of each:
Если элементы управления, необходимые приложению, недоступны в окне Источники данных , можно добавить элементы управления. If the controls your application needs are not available from within the Data Sources window, you can add controls. Дополнительные сведения см. в разделе Добавление пользовательских элементов управления в окно Источники данных. For more information, see Add custom controls to the Data Sources window.
Кроме того, можно перетаскивать элементы из окна Источники данных на элементы управления, которые уже находятся в форме, чтобы привязать элемент управления к данным. You can also drag items from the Data Sources window onto controls already on a form to bind the control to data. Элементы управления, которые уже привязаны к данным, применяют привязку данных к элементу, который был перемещен в последнее время. A control that is already bound to data has its data bindings reset to the item most recently dragged onto it. Чтобы быть допустимым целевым объектом перетаскивания, элементы управления должны иметь возможность отображения базового типа данных элемента, перетаскиваемого в него, из окна Источники данных . To be valid drop targets, controls must be capable of displaying the underlying data type of the item dragged onto it from the Data Sources window. Например, нельзя перетащить элемент, имеющий тип данных DateTime CheckBox , на, поскольку не CheckBox может отобразить дату. For example, it’s not valid to drag an item that has a data type of DateTime onto a CheckBox, because the CheckBox is not capable of displaying a date.
Привязка к данным в отдельных элементах управления Bind to data in individual controls
При привязке источника данных к подробностям каждый столбец в наборе данных привязывается к отдельному элементу управления. When you bind a data source to Details, each column in the dataset is bound to a separate control.
Обратите внимание, что на предыдущем рисунке вы перетащили из свойства Orders таблицы Customers, а не из таблицы Orders. Note that in the previous illustration, you drag from the Orders property of the Customers table, not from the Orders table. При привязке к Customer.Orders свойству команды навигации, выполненные в DataGridView , немедленно отражаются в элементах управления «подробности». By binding to the Customer.Orders property, navigation commands made in the DataGridView are reflected immediately in the details controls. При перетаскивании из таблицы Orders элементы управления все равно будут привязаны к набору данных, но не будут синхронизированы с DataGridView. If you dragged from the Orders table, the controls would still be bound to the dataset, but not they would not be synchronized with the DataGridView.
На следующем рисунке показаны элементы управления, привязанные к данным по умолчанию, которые добавляются в форму после привязки свойства Orders в таблице Customers к сведениям в окне Источники данных . The following illustration shows the default data-bound controls that are added to the form after the Orders property in the Customers table is bound to Details in the Data Sources window.
Обратите внимание, что каждый элемент управления имеет смарт-тег. Note also that each control has a smart tag. Этот тег включает настройки, применяемые только к этому элементу управления. This tag enables customizations that apply to that control only.