1. Introduction The BindingSource component is a bridge between data sources and controls, and provides a large number of APIs and events for us to use. Using these APIs, We can decouple Code from various data sources. Using these events, we can gain insight into data changes. 2. simply bind DataTable myTable = myTableAdapter. getData (); // CREATE Table BindingSource myBindingSource = new BindingSource (); // create BindingSource DataGridView myGrid = new DataGridView (); // create a GridView myGrid. dataSource = myBindingSource; // BindingSource to the GridView myTable; // bind data to the BindingSource. Note: 1) bind data to the able, which is actually bound to the DataView provided by the DataTable. Each able has a default DataView. 2) DataView is the essence of the binding. Just like its name, it represents the data of the DataTable. Therefore, you can construct multiple dataviews for the same able, and implement different filtering and sorting methods for the same data to display the DataTable from different aspects. This also reflects some MVC ideas. 3) BindingSouce can also be transferred between different forms as a data (actually a Data Reference) container, so as to edit the data in the pop-up Form 3. the data shown in the image of the primary table is used as an example: 1) DataSet: myDataSet 2) able: ParentTable, ChildTable, GrandChildTable 3) Relation: FK_Parent_Child, FK_Child_GrandChild // bind the parent data parentBindingSource. dataSource = myDataSet; parentBindingSource. dataMember = "ParentTable"; m_GrandParentGrid.DataSource = m_GrandParentBindingSource; // bind the child data. ChildBindingSource. dataSource = parentBindingSource; // bind to "parent BindingSource" instead of the parent Table childBindingSource. dataMember = "FK_Child_GrandChild"; // bind to "Parent-Child Relation" // bind the child data. GrandChildBindingSource. dataSource = childBindingSource; // bind it to "sub-BindingSource" grandChildBindingSource. dataMember = "FK_Child_GrandChild"; // bind it to "child-sun Relation" so that you can put three dataviews on the Form and bind them to the three BindingSouce, it is easy to implement the association presentation of the primary table. 4. To manipulate data, you must first obtain the current data item. The Current attribute of BindingSource returns the DataRowView type object (just as DataView encapsulates the DataRow), which encapsulates the Current data item, you can convert the data type to the desired object. DataRowView currentRowView = myBindingSource. current; // obtain the Current RowView CustomersRow custRow = currentRowView. row as CustomersRow; // type conversion to the current data item string company = custRow. companyName; // use the current data item string phoneNo = custRow. phone; 5. using BindingSource as a data container BindingSource can also be used as a data container. Even if it is not bound to a data source, it has a list that can hold data. 5.1Add method call the Add method inserts data items in the list of BindingSource. If the data is inserted for the first time, and no data is bound, the type of the inserted data determines the data type in the list in the future. Note: 1) inserting another type of object will throw an InvalidOperationException. 2) the list will be refreshed when the DataSource attribute is set, this results in data loss in the Add method added to the list. The 5.2AddNew method AddNew method returns the objects of the Data Type that BindingSourc holds. If the data is not previously accommodated, the Object is returned. The AddNew method calls the EndEdit method and submits operations on the current data. The new data item becomes the current data item. The AddNew method triggers the AddingNew event. You can assign values to data items in this event, or create a new data item private void OnAddingNew (object sender, AddingNewEventArgs e) {e. newObject = new MyCustomObject (); //} 6. bindingSource is used to Sort, filter, and search data. 6.1 Sort is assigned with an Sort expression for the Sort attribute. You can Sort data by using myBindingSource. sort = "ContactName ASC"; // Sort the ContanctName column by ASC. sort = "Region ASC, CompanyName DESC" // Sort by Region and CompanyName first. 6.2 The Find method searches by specified attributes and keywords and returns the Inde of the first matching object. X int index = m_CustomersBindingSource.Find ("CompanyName", IBM); // search for IBM if (index! =-1) {myBindingSource. position = index; // locate BindingSource} 6.3 Filter is an expression assigned to the Filter attribute, which can Filter data m_mermersbindingsource.filter = "Country = 'Germany '"; // filter out the data whose Country attribute is Germany. event monitoring data 7.1 Event 1) AddingNew is triggered when the AddNew () method is called. 2) BindingComplete is triggered when the Control completes data binding, indicating that the control has read the value of the current data item from the data source. This event is triggered when BindingSource is rebound or the current data item changes. Note: * when multiple controls are bound to the same data source, this event is triggered multiple times. 3) this event is triggered when the current data item changes. This event is triggered as follows * When the Position attribute is changed * when data is added or deleted * When the DataSource or DataMember attribute is changed 4) when the value of the current data item changes CurrentItemChanged 5) when DataError normally inputs invalid data, CurrencyManage throws an exception to trigger this event. 6) This event is triggered when the PositionChanged Position attribute is changed. 7) triggered when the ListChanged Data Set changes. This event is triggered as follows * when adding, editing, deleting, or moving data items change the attributes that affect the List behavior features, such as AllowEdit attribute * When replacing the List (bound to the new data source) 8. limiting data modification to BindingSource is not only a "bridge" between the data source and the control, but also a "Gatekeeper" of the data source ". Through BindingSource, we can control the modification of data. The AllowEdit, AllowNew, and AllowRemove attributes of BinidingSource can control the modification of data by client code and controls 9. binding of complex data types directly binds String data to the Text control. For complex data types, there are the following situations: * For DateTime, Image, and other types of data, their storage formats are inconsistent with the display requirements. * Sometimes, you do not want to display the customer ID, but want to display the customer name * The Null Value of the database is 9.1. The key to solving the above problem is to understand the Binding class, understand how it controls data Binding. DataTable table = customersDataSet. MERs MERS; // bind the Text attribute of TextBox to the CustomerID column customerIDTextBox of table. dataBindings. add ("Text", table, "CustomerID", true); // The above line of code is equivalent to the following two lines of code Binding customerIDBinding = new Binding ("Text", table, "CustomerID", true); customerIDTextBox. dataBindings. add (customerIDBinding); the Code shows that Binding is the intermediary between the data source (table) and the control (customerIDTextBox). It has the following functions: * retrieving data from the data source, and format the data according to the data type required by the control (Fo Rmatting), and then pass it to the control * to retrieve data from the control and parse the data according to the Data Type Requirements of the data source (Parsing ), then return to the data source * automatically convert the data format. 9.2Binding constructor and attribute Binding constructor have multiple overloaded versions. The following describes important parameters, these parameters exist in the Binding object attributes at the same time. In the following section, the parameter name and attribute name are listed. 1) formattingEnabled (attribute FormattingEnabled) o true. The Binding object is automatically converted to o false between the data source type and the type required by the control. 2) dataSourceUpdateMode determines when the value changes on the control are submitted back to the data source. 3) values corresponding to nullValue DBNull, null, and Nullab <T>. 4) formatString Format conversion 5) formatInfo is an object reference that implements the IFormatProvider interface. To learn how to convert types by using custom Format conversion, learn about Type Conversions and Format Providers. For more information about the application of the above attributes, see section 9.3 about the parameters or attribute settings when constructing a type conversion using the Binding Class Based on the built-in mechanism (attributes and parameters) of the Binding class, you can control its type conversion mechanism. 1) the following section describes an example of the DateTime type. Use the DateTimePicker control // to create a Binding and set formattingEnabled to true birthDateTimePicker. dataBindings. add ("Value", m_EmployeesBindingSource, "BirthDate", true); // set it to use the custom format birthDateTimePicker. format = DateTimePickerFormat. custom; // set the format of birthDateTimePicker. customFormat = "MM/dd/yyyy"; 2) Numeric salaryTextBox. dataBindings. add ("Text", employeesBindingSource, "Salary", true, Objective C EUpdateMode. onValidation, "<not specified> ","#. 00 "); the above Code does the following: * Set formattingEnabled to true: Indicates automatic type conversion * sets performanceupdatemode to OnValidation: * sets nullValue to" <not specified> ": these DBNull values are displayed as "<not specified>". When the user inputs "<not specified>", the data value is DBNull * and the formatString is set "#. 00 ": the value is retained with 2 decimal places of 9.4. the following describes the main events of Binding and how to control type Conversion Based on these events. Main Event: 1) the Format event occurs after the data is obtained from the data source, before the control displays the data. In this event, convert the Data Type of the data source to the data type required by the control. 2) The Parse Event is opposite to the Event. It changes the control value before the data is updated back to the data source. In this event, convert the Data Type of the control to the data type required by the data source. These two events provide a mechanism for us to control data. They are declared as the ConvertEventHandler type, void ConvertEventHandler (object sender, ConvertEventArgs e); there are two parameters, the second parameter ConvertEventArgs e provides the data for formatting and parsing. It has two attributes: * e. DesiredType, which is the target type of the Value to be converted * e. Value, which is the Value to be converted. We can replace this Value9.5. Event-based type conversion 9.5.1 processing Format Event void OnCountryFromFormat (object sender, ConvertEventArgs e) {if (e. value = null | e. value = DBNull. value) {pictureBox. image = null; return;} // bind the CountryID field of the data source, so e. the ID number returned by the Value. The corresponding data row CountriesRow countryRow = GetCountryRow (int) e. value); // convert e. value is assigned to CountryName, so that the name e is displayed in the control. value = countryRow. countryName; // data conversion ImageConverter convert Er = new ImageConverter (); pictureBox. image = converter. convertFrom (countryRow. flag) as Image;} 9.5.2 process Format Eventvoid OnCountryFromParse (object sender, ConvertEventArgs e) {// Need to look up the Country information for the country nameExchangeRatesDataSet. countriesRow row = GetCountryRow (e. value. toString (); if (row = null) {string error = "Country not found"; m_ErrorProvider.SetError (m_CountryFro MTextBox, error); m_CountryFromTextBox.Focus (); throw new ArgumentException (error);} e. value = row. countryID;} 10 This is often the case when you complete data editing. You can enter or select some data in a control. Only when you leave the control that year can the associated data be synchronously updated. This problem is determined by the internal mechanism of DataRow. The DataRowView class implements the IEditableObject interface and supports transactional editing of objects (data can be rolled back before you confirm that the editing is complete ). We use the BeginEdit () method to start data editing and use the EndEdit () method to submit and edit the data. Do not confuse the EndEdit () of DataRowView with the AcceptChanges () method of DataSet, DataTable, and DataRow. DataRow has original and current versions, and the IEditableObject caching mechanism allows it to have a transient version. data modification is not submitted to the data source before the EndEdit () method is called. This is the internal cause of the problem. If you want to submit the edited data immediately, the best place to call the EndEdit () function is the Validated event. The Validate event is triggered after the data is parsed input by the Control and triggered after the validate event. If this event triggers EndEdit (), it notifies all the controls bound to the same data source to implement data synchronization and update. Private void OnCountryTextValidated (object sender, EventArgs e) {exchangeRatesBindingSource. endEdit ();} Of course, when the current data item changes, it will also trigger the EndEdit () event 11. Use AutoComplete. If you want TexbBox or ComboBox to automatically prompt the function, then you should learn about the AutoComplete function. The following uses TextBox as an example to describe how to set the AutoCompleteSource attribute of TextBox: FileSystem, HistoryList, RecentlyUsedList2) If you want to use a custom list, set the AutoCompleteSource attribute to customsoure3) set AutoCompleteMode to SuggestAppend. This means that when you enter some characters, the control will prompt all similar data in the drop-down list. 4) If you do not want to use the built-in prompt source, you can create a list of AutoCompleteStringCollection classes by yourself. 5) after creating this list, it is critical to assign it to the DataSourceUpdateMode attribute of BindingSource of the lifecycle of 12 DataBinding to the AutoCompleteCustomSourc attribute of TextBox. It has three possible values, the following uses the TextBox control as an example to describe the lifecycle of DataBinding when this attribute is different. 1) OnValidating (default) * lifecycle of DataBinding: TextBox. leave, TextBox. validating, Binding. parse, TextBox. validated * If the CausesValidation attribute of the control is set to false, the Validating event 2) OnPropertyChanged * DataBinding lifecycle: Binding. Parse is triggered every time the control value changes. For the TextBox Control, Binding. Parse is triggered every time a character is entered. 3) The Never Parse event will not be triggered at this time, that is, the control will become read-only. 13 The Sub-parent binding describes master-slave binding. It is actually a parent-child binding. Sometimes we want to bind the child to the parent, and we will implement this mechanism together. The key to implementing this mechanism is Event. This Event is the CurrentChanged Event private void OnCurrentChanged (object sender, EventArgs e) of BindingSource {// obtain the current subdatarow ExchangeRatesDataSet. exchangeRatesRow currentRow = (ExchangeRatesDataSet. exchangeRatesRow (DataRowView) m_ExchangeRatesBindingSource.Current ). row; // obtain the associated parent DataRow ExchangeRatesDataSet. countriesRow fromCountryRow = currentRow. countriesRowByFK_ExchangeRates_Countries From; ExchangeRatesDataSet. CountriesRow toCountryRow = currentRow. CountriesRowByFK_ExchangeRates_CountriesTo; // displays the information of the parent DataRow if (fromCountryRow! = Null & toCountryRow! = Null) {m_FromCountryCombo.SelectedValue = fromCountryRow. countryID; m_ToCountryCombo.SelectedValue = toCountryRow. countryID ;}} 14 when multiple copies bound to the data are available, we want to see the same data from different angles. In this case, we need to bind multiple copies to the same data. The key here is the CurrencyManager class. Each BindingSource manages a CurrencyManager. If multiple controls are bound to the same BindingSource, there is only one CurrencyManager, so there is only one CurrentItem, which causes these controls bound to the same BindingSource to be refreshed synchronously. To solve this problem, we need multiple currencymanagers, that is, we can create multiple bindingsources and bind them to the same data source. 9.5 There are two concepts for processing the Null type. Net built-in Null type and represents the Null type in the database, and their differences. 1 ). net built-in Null type * Nullable, reference type * Nuallable <T>, Value Type 2 ). net is used to represent the Null type * DBNull in the database. It has an attribute Value that can be used to determine whether the data is DBNull if (northwindDataSet. employees [0]. country = DBNull. value) {// Handle null case here} for a strong-type dataset if (northwindDataSet. employees [0]. isCountryNull () {// Handle null case here} 1) AddNew () function: Used to add a piece of data. The return type is determined by the bound DataSource. 1) When bound to DataSet/able, the DataRowView object is returned. Note: a) the returned data is not DataSet, able, or DataRow. B) If you want to obtain the added data, type conversion is required. // The BindingSource DataRow row = (DataRow) (DataRowView) bs created by bs for you. addNew ()). row; c) When TypedDataSet is used, the conversion method is similar to the preceding one. Only TypedDataRow is used. // The TypedDataRow MyDataRow row = (MyDataRow) (DataRowView) bs. addNew ()). row;
The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion;
products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the
content of the page makes you feel confusing, please write us an email, we will handle the problem
within 5 days after receiving your email.
If you find any instances of plagiarism from the community, please send an email to:
info-contact@alibabacloud.com
and provide relevant evidence. A staff member will contact you within 5 working days.
A Free Trial That Lets You Build Big!
Start building with 50+ products and up to 12 months usage for Elastic Compute Service