Download as pdf
Download as pdf
You are on page 1of 8
sro Data Binding in NET / C# Windows Forms “{8sck Data Binding in .NET / C# Windows Forms More Information on installing the .Net Framework click here. Download full Visual Studio C# .NET Example from this Article Contents Overview Binding Context CurrencyManager Bindable Data Sources Array or Collection ADO.NET Data Objects DataColumn Datatable Dataview Dataset DataViewManager Example: Automatically synchronized Master-D: Managing Data Relation Binding to a DetaGrig Binding to-a Combobox Example: Form's BindingContext Position Management Handling of the PositionChanged event for the Form's BindingContext Format and Perse Events of the Binding Class Example: Binding to 2 ComboBox or ListBox Bind @ ComboBox to an array of State objects Overview Data binding provides a way for developers to create a read/write link between the controls on a form and the data in their application (their data model). Classically, data binding was used within applications to take advantage of data stored in databases. Windows Forms data binding allows you to access data from databases as well as data in other structures, such as arrays and collections. Binding Context Each Windows Form has at least one BindingContext object that manages the CurrencyManager objects for the form. For each data source on a Windows Form, there is a single CurrencyManager object. Because there may be multiple data sources associated with a Windows Form, the BindingContext object enables you to retrieve any particular CurrencyManager object associated with a data source, Example For example if you add a TextBox control to a form and bind it to @ column of a table (¢.9. "Customers. FirstName") in 2 dataset (¢.9, "dsCust"), the control communicates with the BindingContext object for that form. Tie BindingContext object, in turn, talks to the specific CurrencyManager object for that data association. If you queried the CurrencyManager's Position property, it would report the current record for that TextBox control's binding. In the example below, 2 TextBox contral is bound to the FirstName column of a Customers table on the dsCust dataset through the BindingContext object for ene form itis on, 1/ Sinple Data Binding ‘tetBox DataBindings Add "Text" ,dsCust, "Customers FirstName"); hitps:wwu.akadia,comiservicesidotnet_databinding, him! 18 sro Data Binding in NET / C# Windows Forms Currencylanager en = (CurrencyManager) this BindingContaxt([dsCust, "Custoners"] ong FowPosition = (Long) en. Position; CurrencyManager ‘The CurrencyManager is used to keep data-bound controls synchronized with each other (showing data from the same record). The CurrencyManager object does this by managing a collection of the bound data supplied by a data source. For each data source associated with a Windows Form, the form maintains at least one CurrencyManager. Because there may be more than one data source associated with a form, the BindingContext object manages all of the CurrencyManager abjects for any particular form. More broadly, all container controls have at least one BindingContext object to manage thelr CurrencyManagers. An important property of the CurrencyManager is the Position property, Currency is @ term used to refer to the currentness of position within a data structure, You can use the Position property of the CurrencyManager class to determine the current position of all controls bound to the same CurrencyManager. For example, imagine @ collection consisting of two columns called "ContactName" and "Phone". Two TextBox controls fre bound to the same data source. When the Position property of the common CurrencyManager is set to the fourth position within that list (corresponding to the fifth name, because It Is zero-based), both controls display the Appropriate values (the fifth “ContactName” and the fifth "Phone far that position in the data source. Examp! For example the Position property of the CurrencyManager is often manipulated in a Next / Prev Navigation Button == J ion to next Recosd in Custones tie void biaNex: Click (object sender, System.EventArgs e} CurrencyManager on = (CurzencyManager) this BindingContaxt (daCust, "Customers"] : if (em. Position < cm.Count ~ 1) ‘ , Bindable Data Sources In Windows Forms, you can bind to a wide variety of structures, fram simple (arrays) to complex (data rows, data Views, and so on), As a minimum, a bindable structure must support the IList interface, As structures are based on increasingly capable interfaces, they offer more features that you can take advantage of when data binding. The list below summarizes the type of structures (data containers) you can bind to and provides some notes about what data-binding features are supported Array or Collection ‘To act as a data source, a list must implement the TList interface; one example would be an array that is an instance of the System Array class. ADO.NET Data Objects ADO.NET provides @ number of data structures sultable for binding to: Datacolumn object — A DataColumn object is the essential building block of @ DataTable, in that 2 umber of columns comprise a table, Each DataCelumn object has a DataType property that determines the kind of data the column holds. Yau can simple-bind a control (such as @ ‘TextBox control's Text property) to a column within a data table. You add simple data bindings by using the DataBindings collection on a control naa 2 DataTable object — A DataTable object is the representation of a table, with rows and columns, in ‘ADO.NET. A data table contains two collections: DataColumn, representing the columns of date ina given table (which ultimately determine the kinds of data that can be entered into that table), ‘and DataRow, representing the ows of data in a given table. You can complex-bind a control to the information contained in a data table (such as binding the DataGrid control to a data table), However, when you bind to a DataTable, you are a really binding to the table's default view You add complex data binding by using the DataSource and DataMember properties: = dscast DataView object — A DataView object is a customized view of a single data table that may be filtered or sorted. A data view is the data "snapshot" used by complex-bound controls. You can simple- or complex-bind to the data within a data view, but be aware that you are binding to a fixed “pleture” of the data rather than a clean, updating data source. © Dataset object — A DataSet object is a collection of tables, relationships, and constraints of the hitps:wwu.akadia,comiservicesidotnet_databinding, him! 28 sro Data Binding in NET / C# Windows Forms data in a database. You can simple- or complex-bind to the data within @ dataset, but be aware that ‘you are binding ta the DataSet’s default DataViewManager (see below. @ DataviewManager object — A DataViewManager object is a customized view of the entire DataSet, analogous to a DataView, but with relations included. A DataViewSettings collection allows you to set default filters and sort options for any views that the DataViewManager has for a given table, Example: Automatically synchronized Master-Detail In database applications, It is often useful to view a record with a group of related records. For example, you may want to view a Customer with the current Orders for that Customer. Each Order should also ¢isplay the current Order Details for this order ee FScT) pay | Mate listen sd licesiees a peser Contag [Prsinetegird lorbatis == Jusba how [ares Pra. a des DideiD | Catowel | FreloeeD [CdaDae | ReyuidDae| Shpea = ye —~«BERSS 1205-198 —OBCETe5e 16087 ozo =«EEGS. 2 ‘Woet9% ticet986 12091 nore «SERGS 3 weriee vaoise7 aa soue = «EERGS yomtee scr 21021 vous BERS yamigy vase mors vos = BEAS Seno am we jt Dela OdeiD [Poa UnPiee [Guaniy [Osean we 185 6 0 vores 6 0 ve 35 e 0 wre 78 2 2 o Managing Data Relation One of the primary functions of a DataRelation is to allow navigation from one DataTable to another within a DataSet. This allows you to retrieve all the related DataRow objects in one DataTable when given a single DataRow from a related DataTable. For example, after establishing a DataRelation between a table af customers and a table of orders, you can retrieve all the order rows for a particular customer row using DataRow.GetChildRows. If you have two controls bound to the same datasource, and you do not want them to share the same position, then you must make sure that the BindingContext member of one control differs from the BindingContext member of the other control. If they have the same BindingContext, they will share the same position in the datasource. If you acd 2 ComboBox and a DataGrid to a form, the default behavior is for the BindingContext member of each of the two controls to be set to the Form's BindingContext. Thus, the default behavior is for the DataGrid and ComboBox to share the same BindingContext, and hence the selection in the ComboBox is synchronized with the current row of the DataGrid, If you do nat want this behavior, you should create a new BindingContext member for at Teast one of the contrals. ablish the Relationship "RelCustord™ between Cuetone orders System.Data batacolunn colMaster 1 2'ds. Tables ("Customers") .Colunn new Sy akelation ("RelCustOrd”, coltiasterl, coldetaill) ; 9 to a DataGrid This sample displays a Datagrid for the Orders and a DataGrid for the Order Details for each Order. The Customer Data is bound to a few Textboxes and 2 Combobox. We will use the Combo Box to select the company name, and display the contact name, phone number and fax number in the text boxes. hitps:wwu.akadia,comiservicesidotnet_databinding, him! ae srreo17 Data Binding in.NET C# Windows Fors [As the selected customer changes, the DataGrid's updates to display the orders and order details for that customer. In order to link the two DataGrid objects, you need to set the DataSource of each DataGrid to the same DataSet, You also need to set the DataMember properties to indicate to the Windows Forms BindingContext that they are related. You do this by setting the DataMember for the DataGrid's to the name of the relationship between the Customers and Orders tables. The same is done for the Orders and Order Details Table. JJ Sexup the grid's view and mesber data grdorders.Datasource = dsVsews Grd0rders DataMenzer ~ "Customers RelCustord”; Binding to a Combobox ‘The Combobox doesn't have a DataMember property ~ Instead it has a DisplayMember and ValueMember Property: @ The DisplayMember of @ Combobox gets or sets a string that specifies the property of the data source whose contents you want to display. @ The ValueMember property determines which value gets moved into the SelectedValue of the ‘Combo Box. In the example, whenever the user selects a Customer by "Customers.CompanyName", the SelectedValue is the "Customers. CustomerID". Whenever the SelectedValue changes, the data- binding moves the new value into the Customer abject. value nenber chcust Displayienber = "Custoners.Companytiane"s epCust ValueMenber ~ "Customers custonerI0"7 c# Code using syste using syster. Using syster teeing System-ComponentHode? Using System Windows.Fores: using syster.Datas Using system Data.sqicilent; haespace Akadia t 11 Shows Master-Detall, Table-Mapping, FL public class Wasterbetail : Systen, window: // fields private DataViewanage: deview: private Dataset de: public Masterdetaa2( ‘ {i Croace Components Eaitiaiizeconponent (1 J] Setup DB-Consection Connectsonstring = "data sourc Salconsection ca ~ new Sqlcennest, ‘id-oa;password-ranagersdatabase=northwind” (Consectionstring) : U1 Create the Dataset ds = new Datager ("custordes: 411 the Dataset wit Customers, map Default Tablenane dal. TableNappings .Add (*Tebie™, "Cus saleiii(as): 411 the Dataset with osders, sap Default Tablename ‘Table" to “Orders” SqlDatandapter da? ~ new SylDataAdapter "SE: a2. TableNappings Add ("Table™, "Orde: gaz -Fillies)? + PROM orders", en): {/ FLlL the Dataset with (ceder Details], map Default TabLename i/ "apie" to "Ordexbetails Sqlpatandapter da ~ new SylDataAdapter ("Sei a3, TableMappings Add ("Tabie™, "OrdorDetaiis"); a3 FLL (a)? st + PROM [Order Detaile]",en): JJ Show created Tablenanes within che Dataset string mylisssage = "rable Mapping for{int ind; i < ds.Tables.counts ++) myMessage 4 i.tosteing() + + ds-tables(t) .tostrieg() ~ hitps:wwu.akadia,comiservicesidotnet_databinding, him! 48 srreo17 Data Binding in.NET C# Windows Fors JJ Retablish the Relationship *Reicustord” {7 between Customers -—~< Orders Systen-Data,DataRelation reiCestOrdi System Data.DataColumn colMaster=+ Syston Data DataColunn colDetat! colMaster! ~ de-Tables ["Custoners”, .Coluens|"CustomertD*} celBetaiil = ds-Tables|"Orders"] .Colunns("Custoner1D FelCustOrd = new Systen.Data.DataRelat ion (*RelCustOrd", colMasterl,coiDetalit}: ds Relavions Add irelCust0=d) | // Bstablish the Relationship "Reloradet" 27 between Orders ~-~< (Osder Detat ls) Syston.bata,DataRelation relordbe System Data DataColunn colMaster2: Systen.Data,DataColumn colDetail: rolWaster? = da.Tables ["O=ders"]-Colunns(*OzdexI0"} colbetaii2 - da-Tables [Morderdeta::s"] .colunns{"ordertD"]; EelOsddet ~ new System.dats.DataRelation ("RelOrdbet",coiMaster2,colDetail2) 2 dg Relations Add (relordDet) } 11 show created Relations within the Dataset for(int 10; 4 < ds.Relations.count; i++) myassage += i.tostring() +" ‘+ ds.Relations [i] .Tostringt) +" ": extWessage.Text = myMessage: / The DataVienManager returned by the DefasltVsewanager 7) property allows you to create custom settings for each i/ DataTable in the. Dataset. daview ~ de. Defaultviewlanagers J Grid Databinding grddrders. datasource = dsviews Grddeders DataMenber = "Custoner#.RelCestor gradrderDetails.JataMember ~ "Custoners.RelGustord.Relordzet”, 1} Combobox Databinding PbCast DataSource = daViews chest Displayiember = "cuetoness.Companykane"; ebCast Valuelenber = "Castoners CustomerID"; 1) Toxe Columns Databinding txtContact. DataSindings -Add ("Text", deView, "Castoners.contactNane"} 7 ExtPhoneNo. Datasindings Add (*Toxt", dsView, "Castomors. Phone"); txtFanto. DataBindings Add("Text", daview, "Custoners Fax" ) J Position to prov Record in Custoner private void binPrev Click(object sender, Sy i sn EventArgs ef Lf (this SindingContent [dsview, "Customers"] Position > 0) tnis.BindingContext [daView, "Customers") Position: JJ Position to next Record in Custoner private void btnNext Click(object sender, sy ‘ len.iventargs @) currencyManager om = (currency? f (en-tosition © em.Count = 1) ager) this. BindingContext [dsview, on. Positiontts // The main entey point for the application. static void Main() 1 Application Run (new Masterbetail())7 , Example: Form's BindingContext Position Management hitps:wwu.akadia,comiservicesidotnet_databinding, him! 58 sro Data Binding in NET / C# Windows Forms This example shows two important features 1. How to handle the position changing events for the Form's BindingContext. ‘We want to display the current Position (Record 1 of 5) on the Panel. 2. How to use the Format and Parse Events of the Form’s BindingContext. ‘We want to format a Textbox (Date of Birth) which shows @ DateTime in short format 3. How to build a strongly typed lst, which implements the IList and IComponont Interface, ‘This list can then be used as a data source. i ox 6 = Me fa Fratane [or Leave Feds Daeogen fsosien sides fTDeck seen these, laces. Handling of the PositionChanged event for the Form's BindingContext ‘The BindingManagerBase.PositionChanged Event occurs when the Position property, managed by the CurrencyManager, changes. If you want to execute you own code, when this event is raised, then you can hook into the position changed event on the BindingContes 2 Bindingtana: Add the delegate for the Positionchanged event 1/ Position has changed - update the “Record X of N" Panel private void custoners_Positionchanged(object sender, System.EventArgs e) « ‘textBoxPasition. Text = String.Format ( *Record {0} of (1)", ( ‘this BingingContext(custList].Position + 1 ), eustList.count >) y Format and Parse Events of the Binding Class There are two events on the binding class that are most useful. They are Format and Parse. These two events ai raised when ever the data is pushed from the data source to the control or when the data is pulled from the control to the data source. This allows you to do special validating and formatting of the date. The Format event is used for formatting the data from the data source before itis displayed on the control. So when data is pushed from the data source to the control in the Format event is raised and you can perform whatever data formatting or validation Is necessary prior to displaying it ‘The Parse event is used when that data Is changed in the control and needs to go back to the data source, A classic exemple of this process would be data that Is stored as a cecimal, but displayed as a currency, The code in the event handler for the Format event would take the decimal value and format it for currency display, while the code In the Parse event handler wil take the currency and convert it back to decimal type, In our example, we want to format the DateOfBirth TextBox the format and To acconplish this, ‘cextBox0OB_ Formatbate) hitps:wwu.akadia,comiservicesidotnet_databinding, him! cry srreo17 Data Binding in.NET C# Windows Fors SobRinding.Parse += new Convortfuentiiandier (this, textBoxOOB_ParseDate) ; textBex008 -Datasindings Ada (doDBinaing) : // Sormat the Date Field to short date form for display in the Textbox private Vold textBexDO FormatDate (object sender, Convertiventargs ©! i Af (e,vesiredtype !- typeof (Datetine)) return: Ef (e.Varue.GetType{) I» typeos(string)) returns ring value ~ (ateing)e.Value e.Vaiue = DateTine. Parse (value): ' aseh (Reception ex) Mossage3ox. Show (ex Message) 7 ' privace vold textBoxD0B_ParseDate (object sender, Convertuventargs e) ‘ / We only deal with converting to strings £ Af (e.DesiedType != typeof (string)) retusn 7 if (e.varue.GetType() I= typeot (DateTime) return ¢ Dacerine dt = (DateTine| e.Value ~ at, Toshort Dates value: ng Example: Binding to a ComboBox or ListBox ‘This sample demonstrates binding data to a ComboBox, Bincing deta toa ListBox follows the same model. To bind data tothe Ist of Kems that are cisplayed, set the DataSource and DisplayMember properties of the ComboBox. The DisplayMember property is used to determine which property of the State object to display in the Combobox. EM alo 1 Gompary [GreatLakscFoodMakst Cane: HowodSwd Ie Fats Adder [F7DBae te tiv [Fe Stole (ER ——____] 2p |Pamsiana rose sand auth cain Seah Bako As pal Bind a ComboBox to an array of State objects namespace Akadia.ConboBoxBinding t ‘ging Syatem.ConponentNodel; ‘ging System. Windows. Forms; using System Tsqiclient: public clase ComboRoxBinding : Systen.WLn public struct state hitps:wwu.akadia,comiservicesidotnet_databinding, him! 718 srreo17 Data Binding in.NET C# Windows Fors public State (string longilane , string shortNne) Shiai zicngtone’ = aenguaney public string ShortName { get { return shortNane; } } public string Longane { get { zeturn Tongtane | | ) // bafine the Arcay of States for the Droplown ist public State(] states ~ new Statel] new State ("Alabara","AL") yen State ("Alaske™, YAR") [ne State ("Arkaneas", spew State ("California Ve public Conboboxsinding() t JY vopwlate the list ‘comboRoxState DataSource = states; {/ detine the field to be displayed ‘combotoxState.DisplayMenber = "LongName"; // define the field co be used as che value ‘comboBoxState.Valuelenber = "ShortKane" ; J] Bind the selected value of the the ComboBox to the /) Sagion field of che current Customer combolloxState DataBindings Add("SelectedValue", custoneraDataSeti, “Custozers Region hitps:wwu.akadia,comiservicesidotnet_databinding, him!

You might also like