Data Binding and Data Grid View Classes


Published on

This is a class presentation, for introducing the concepts of Data Binding and Data Grid View Classes in C# and .NET

Published in: Education, Technology, Business
  • Be the first to comment

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide

Data Binding and Data Grid View Classes

  2. 2. OVERVIEW• SIMPLE AND COMPLEX DATA BINDING• ONE-WAY AND TWO-WAY DATA BINDING• Binding and BindingManagerBase classes• Sample Data Binding Application• DataGridView class
  3. 3. DATA BINDINGLink the contents of a control with an underlying data source
  4. 4. WHY DATA BINDING?• Changes to the immediate data source can be reflected automatically in data controls bound to it • Changes in the data control are posted automatically to the intermediate data source
  5. 5. INTERMEDIATE DATA SOURCEThe term intermediate data sourceis used to distinguish it from theoriginal data source, which may bean external database
  6. 6. IMPORTANT NOTEThe controls cannot be bounddirectly to a data source over anactive connection.Binding is restricted to the in-memory representation of the data.
  8. 8. SIMPLE DATA BINDINGSimple data binding, which isavailable to all controls, links a datasource to one or more properties ofa control.
  9. 9. DATA BINDING WITH A TEXTBOXAn application can set properties of a textboxdynamically by binding them to a datasource.The following program creates an objectwhose public properties are mapped to theproperties on the TextBox
  10. 10. Simple data binding code// Create object (width, text, color)TextParms tp = new TextParms(200, "Casablanca", Color.Beige);Method 1:// Bind text and BackColor properties of controltxtMovie.DataBindings.Add("Text", tp, "Tb_Text");txtMovie.DataBindings.Add("BackColor", tp, "Tb_Background");Method 2:Binding binding = new Binding("Width", tp, "Tb_Width");txtMovie.DataBindings.Add(binding);
  11. 11. Where the class TextParams is…public class TextParams{ private int Tb_Width; private string Tb_Text; private Color Tb_Color; public TextParams(int width, string text, Color color) { Tb_Width = width; Tb_Text = text; Tb_Color = color; }};//with corresponding get and set method for the propertiesaccessing each data member
  12. 12. DATA BINDING ADD METHODThe DataBindings.Add methodcreates a collection of bindings thatlinks the data source to the controlsproperties.
  13. 13. SYNTAXDataBindings.Add( control property, datasource, data member)control property Property on the control that is being source Object that contains data being bound to member Data member on the data source that is being used. Set this to null if the data sources ToString() method provides the value.
  14. 14. MULTIPLE BINDINGSA control may have multiple bindingsassociated with it, but only one perproperty.This means that the code used to createa binding can be executed only once; asecond attempt would generate anexception.
  15. 15. Multiple BindingsTo avoid this, each call to add a binding should bepreceded with code that checks to see if a bindingalready exists; if there is a binding, it should beremoved.if (txtMovie.DataBindings["Text"] != null) txtMovie.DataBindings.Remove(txtMovie.DataBindings["Text"]);txtMovie.DataBindings.Add("Text", tp, "Tb_Text");
  16. 16. BINDING TO A LISTInstead of binding to a single object, thecontrol can be bound to an array.The control can still only display a singlemovie title at a time, but we can scrollthrough the array and display a different titlethat corresponds to the current array itemselected.
  18. 18. The simple part// ArrayList of TextParms objectsArrayList tbList = new ArrayList();tbList.Add(new TextParms(200,"Casablanca",Color.Beige));tbList.Add(new TextParms(200, "Citizen Kane", Color.White));tbList.Add(new TextParms(200, "King Kong", Color.White));// Bind to properties on the TextboxtxtMovie.DataBindings.Add("Text", tbList, "Tb_Text");txtMovie.DataBindings.Add("BackColor", tbList, "Tb_Background");txtMovie.DataBindings.Add("Width", tbList, "Tb_Width");
  19. 19. SIMPLE BINDING WITH ADO .NETBinding to a table in a DataSet isbasically the same as binding to a list.For example, the Text property of thecontrol is bound to the movie_Yearcolumn in a DataTable.
  20. 20. Binding to a DataSetds = new DataSet("films");string sql = "select * from movies order by movie_Year";da = new SqlDataAdapter(sql, conn);da.Fill(ds,"movies"); // create datatable "movies"// Bind text property to movie_Year column in movies tabletxtYr.DataBindings.Add("Text", ds,"movies.movie_Year");
  21. 21. NOTE…Although the control could be bound directlyto a DataTable, the recommended approachis to bind the property to a DataSet and usethe DataTable name as a qualifier to specifythe column that provides the data.This makes it clear which table the value iscoming from.
  22. 22. COMPLEX DATA BINDING WITHLIST CONTROLSComplex binding is only available on controlsthat include properties to specify a datasource and data members on the data source.This select group of controls is limited to theListBox, CheckedListBox, ComboBox,DataGrid, and DataGridView.
  23. 23. ListBox bound to a DataSetda.Fill(ds,"movies");DataTable dt = ds.Tables[0];// Minimum properties to bind listbox to a DataTablelistBox1.DataSource = ds;listBox1.DisplayMember = "movies.movie_Title";
  24. 24. SOME FINER DETAILS…• After these values are set, the list box is automatically filled.• The DataSource property can be changed programmatically to fill the control with a different set of data• Can be set to null to clear the controls content.• Although no Binding object is explicitly created, a DataBindings collection is created underneath and is accessible through code.
  25. 25. GROUPING WITH OTHERCONTROLSBound list box control is often grouped withother controls, such as a text box or label, inorder to display multiple values from a row ofdata. When the controls are bound to thesame data source, scrolling through the listbox causes each control to display a valuefrom the same data row.
  26. 26. An example…txtStudio.DataBindings.Add("Text", ds,"");txtYear.DataBindings.Add("Text", ds,"movies.movie_Year");
  27. 27. ONE-WAY AND TWO-WAY DATABINDINGData bound to a control can be changed in twoways:• By updating the underlying data source• By modifying the visible contents of the control.Changes should be reflected in the associatedcontrol or data in both cases.This is called TWO-WAY Binding.
  28. 28. ONE-WAY BINDINGA control may be bound to a data source in read-only mode when its only purpose is to present data.The data-source must be “write-protected”
  29. 29. Updating a Control ValueIn the case where a control is bound to a property on an object, theproperty must provide write support in order for its value to be updated.public int Movie_Year{ set { myYear = value; } get { return myYear; }}// Read only property. Control cannot update this.public string Studio { get { return myStudio; } }
  30. 30. Updating a propertyIf a control is bound to an object property, a change to the value of thatproperty is not automatically sent to the control.Instead, the binding manager looks for an event named propertyChangedon the data source// Event to notify bound control that value has changedpublic event EventHandler Movie_YearChanged;// Property control is bound to year valuepublic int Movie_Year { set { myYear = value; // Notify bound control(s) of change if (Movie_YearChanged != null) Movie_YearChanged(this, EventArgs.Empty); } get { return myYear; }}
  31. 31. ADDING OR DELETING AN ITEMFROM THE DATA SOURCEControls that are bound to the sourceusing simple binding are updatedautomatically; controls using complexbinding are not.In the latter case, the update can beforced by executing the Refresh methodof a CurrencyManager object
  32. 32. USING BINDING MANAGERS• Each data source has a binding manager that keeps track of all connections to it.• When the data source is updated, the binding manager is responsible for synchronizing the values in all controls bound to the data.• Conversely, if a value is changed on one of the bound controls, the manager updates the source data accordingly. A binding manager is associated with only one data source.• If an application has controls bound to multiple data sources, each will have its own manager.
  34. 34. COORDINATING THE TWO-WAY FLOWOF DATA BETWEEN A DATA SOURCE ANDCONTROL• Binding// Create a binding manager objectBindingManagerBase mgr= binding.BindingManagerBase;• CurrencyManager • Bindings • Count • Current • Position • PositionChanged • CurrentChanged
  35. 35. COORDINATING THE TWO-WAY FLOWOF DATA BETWEEN A DATA SOURCE ANDCONTROL• PropertyManager : This class, which also derives from BindingManagerBase, maps the properties on an object to properties on a bound control.• BindingContext : A programs main interest in the BindingContext is to use it to gain access to the binding manager for a data source. BindingManagerBase mgr = this.BindingContext[ds,"movies"]; // Or use casting to get specific manager. CurrencyManager mgr= (CurrencyManager) this.BindingContext[ds,"movies"];
  36. 36. Using the BindingManagerBase to Navigate a list// Bind listbox to a dataset.datatablelistBox1.DataSource = ds;listBox1.DisplayMember = "movies.movie_Title";// Bind to TextBoxtxtStudio.DataBindings.Add("text", ds, "");// BindingManagerBase bmb has class-wide scopebmb = this.BindingContext[ds, "movies"];// Create delegate pointing to event handlerbmb.PositionChanged += new EventHandler(bmb_PositionChanged);
  37. 37. USING THE POSITIONCHANGED EVENTThe PositionChanged event is fired each timethe binding manager moves to a new positionin the list.This could be triggered programmatically orby the user clicking a row in the list boxcontrol.
  38. 38. PositionChanged Eventprivate void bmb_PositionChanged(object sender,EventArgs e){ BindingManagerBase bmb = (BindingManagerBase)sender; // Item should be a DataRowView if from a table object ob = bmb.Current.GetType(); if (ob == typeof(System.Data.DataRowView)) { DataRowView view = (DataRowView)bmb.Current; // Could access: ((string)view["movie_Title"]); }}
  39. 39. A sample application . . .
  41. 41. WHAT IS IT?With more than a hundred properties andmethods, the DataGridView is by far the mostcomplex Windows Forms control fordisplaying data.
  42. 42. KEY FEATURES• Data binding is supported by the DataSource property.• DataGridView provides a unique virtual mode that permits it to handle more than 100,000 rows of data.• DataGridView methods, events, and properties allow an application to easily manage the mapping between virtual and physical storage.
  43. 43. PROPERTIES• Elegantly simple structure• Consists of column headers, row headers and cells• To these, we can add the Columns and Rows collections that allow an application to access the grid by indexing a row or column
  45. 45. 5 ELEMENTARY STEPS1. Define column headers2. Define style for data cells3. Define style for column headers4. Define user capabilities5. Place data in grid (manually or using datasource)
  46. 46. DATABINDING WITH A DATAGRIDVIEW• A DataGridView is bound to a data source using complex binding• A DataGridView must display multiple data values• DataMember property is set to the name of a table within the data source
  47. 47. USING A DATA SOURCE// Turn this off so column names do not come from datasourcedataGridView1.AutoGenerateColumns = false;// Specify table as data sourcedataGridView1.DataSource = ds; // DatasetdataGridView1.DataMember = "movies"; // Table in dataset// Tie the columns in the grid to column names in the datatabledataGridView1.Columns[0].DataPropertyName = “movie_title";dataGridView1.Columns[1].DataPropertyName = “movie_year";dataGridView1.Columns[2].DataPropertyName = “studio";
  49. 49. OTHER INTERESTING PROPERTIES• Frozen Columns• ReadOnly Columns• Minimum Width• Sorting• Multiple Column Types : Six predefined column classes are available that can be used to represent information in a grid, : TextBox, CheckBox, Image, Button, ComboBox, and Link. The name for each of these controls follows the format DataGridViewControlnameColumn.
  50. 50. EXAMPLEDataGridViewButtonCell aButton =new DataGridViewButtonCell ();and similarly for other 5 controls.
  51. 51. EVENTSJust about every mouse and cursormovement that can occur over aDataGridView can be detected by one ofits events
  52. 52. CellValueChanged (1) Occurs when the value of a cell changes. CurrentCellChanged (3) Occurs when the value of the current cell changes CellClick (1) Occurs when any part of the cell is clicked. This includes cellCell actions borders and padding. CellContentClick (1) Occurs only if the cell content is clicked. CellEnter (1) Occurs when cell receives/loses CellLeave (1) input focus. CellFormatting (5) Occurs prior to formatting a cell for display. CellMouseClick (2) Occurs whenever a mouse CellMouseDoubleClick (2) clicks/double clicks anywhere on a cell. CellMouseDown (2) Occurs when a mouse button is CellMouseUp (2) pressed/raised while it is over a cell CellMouseEnter (1) Occurs when the mouse pointer CellMouseLeave (1) enters or leaves a cells area. CellPainting (6) Raised when a cell is to be painted.
  53. 53. Column actions ColumnHeaderMouseClick (2) Occurs when a column header is ColumnHeaderMouseDouble-Click (2) clicked/double clicked.Row actions RowEnter (1) Occurs when a row receives/loses the RowLeave (1) input focus. RowHeaderMouseClick (2) Occurs when a user clicks/double clicks RowHeaderDoubleMouse-Click (2) a row header UserAddedRow (4) Occurs when a user adds/deletes a row UserDeletedRow (4) in the grid.Data error DataError (7) Occurs when an external data parsing or validation operations fails. Typically occurs due to an attempt to load invalid data into a data grid cell.
  54. 54. Associated Delegates(1) public sealed delegate void DataGridViewCellEventHandler(object sender,DataGridViewCellEventArgs e)(2) public sealed delegate void DataGridViewCellM_useEventHandler(object sender,DataGridViewCellMouseEventArgs e)(3) public sealed delegate void EventHandler(object sender, EventHandlerArgs e)(4) public sealed delegate void DataGridViewRowEventHandler(object sender,DataGridViewRowEventArgs e)(5) public sealed delegate void DataGridViewCellFormattingEventHandler(objectsender, DataGridViewCellFormattingEventArgs e)(6) public sealed delegate void DataGridViewCellPaintingEventHandler(object sender,DataGridViewCellPaintingEventArgs e)(7) public sealed delegate voidDataGridViewDataErrorEventHandler(object sender,DataGridViewDataErrorEventArgs e)
  55. 55. SOME IMPORTANT EVENTS1. Cell Formatting : The CellFormatting event gives you the opportunity to format a cell before it is rendered. This comes in handy if you want to distinguish a subset of cells by some criteria.2. Recognizing Selected Rows, Columns, and Cells3. Data Error Handling : The DataError event fires when a problem occurs loading data into a grid or posting data from the grid to the underlying data store.
  56. 56. MASTER-DETAIL DATAGRIDVIEWSRecords in the master table have multipleassociated records in the detail table
  57. 57. MASTER-DETAIL DATAGRIDVIEWS• The master grid is bound to the movies table• Details grid is bound to the actors table.• Both tables, as shown, contain the columns that are bound to their respective DataGridView columns.• In addition, they contain a movieID column that links the two in the master-detail relationship.
  58. 58. NEED FOR VIRTUAL MODE• When a DataGridView is bound to a data source, the entire data source must exist in memoryDetails grid is bound to the actors table. Enables quick refresh of control’s cellsХ Large data store may have prohibitive memory requirements.
  59. 59. VIRTUAL MODE• To handle excessive memory requirements, a DataGridView can be run in virtual mode by setting its VirtualMode property to True.• In this mode, the application takes responsibility for maintaining an underlying data cache to handle the population, editing, and deletion of DataGridView cells based on actions of the user.• The cache contains data for a selected portion of the grid
  60. 60. SO WHAT’S COOL?If a row in the grid cannot besatisfied from cache, the applicationmust load the cache with thenecessary data from the originaldata source
  62. 62. VIRTUAL MODE EVENTSThese events are triggered only in virtual mode.Event DescriptionNewRowsNeeded Virtual mode event. Occurs when a row is appended to the DataGridView.CellValueNeeded Virtual mode event. Occurs when cell in grid needs to be displayed.CellValuePushed Virtual mode event. Occurs when a cell value is edited by the user.RowValidated Occurs when another row is selected.UserDeletingRow Occurs when a row is selected and the Delete key is pressed.
  63. 63. TRIGGERED EVENT HANDLERS• RowNeeded : Is triggered when the user begins to add a new row at the bottom of the grid. currRow is set to the row number of any row being added.• CellNeeded : Is triggered when a cell needs to be redrawn. This does not require that a row be selected, but occurs as you move the cursor over cells in the grid. This routine identifies the column the cell is in and displays the data from the cache or the object that is created for new rows. Note that the MapRow() is called to translate a row in the grid to its corresponding row in the cache. In this simple example, there is always a one-to-one relationship because the cache and grid contain the same number of rows. In a production application, row 5000 in a grid might map to row 1 in the cache.
  64. 64. TRIGGERED EVENT HANDLERS(CONTD…)• CellPushed : Called when a cell value is edited. This routine updates a movie object that represents the selected row with the new value.• RowValidated : Signals that a different row has been selected and is used to update the previous row. If the row exists in the cache, it is updated; a new row is added to the cache.• RowDeleting : Called when user selects a row to delete. If the row exists in the cache, it is removed.
  65. 65. THANK YOU FOR YOURPATIENCE Slides Prepared and presented by : ARVIND KRISHNAA J