SlideShare a Scribd company logo
DATA BINDING AND
DATA GRID VIEW CLASS


               A PRESENTATION BY
                Arvind Krishnaa J
OVERVIEW
• SIMPLE AND COMPLEX DATA BINDING
• ONE-WAY AND TWO-WAY DATA BINDING
• Binding and BindingManagerBase classes
• Sample Data Binding Application
• DataGridView class
DATA BINDING


Link the contents of a control with an
       underlying data source
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
INTERMEDIATE DATA SOURCE

The term intermediate data source
is used to distinguish it from the
original data source, which may be
an external database
IMPORTANT NOTE
The controls cannot be bound
directly to a data source over an
active connection.
Binding is restricted to the in-
memory representation of the data.
MULTIPLE CONTROLS BOUND TO A
SINGLE DATA SOURCE
SIMPLE DATA BINDING

Simple data binding, which is
available to all controls, links a data
source to one or more properties of
a control.
DATA BINDING WITH A TEXTBOX
An application can set properties of a textbox
dynamically by binding them to a data
source.
The following program creates an object
whose public properties are mapped to the
properties on the TextBox
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 control

txtMovie.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);
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 properties
accessing each data member
DATA BINDING ADD METHOD


The DataBindings.Add method
creates a collection of bindings that
links the data source to the control's
properties.
SYNTAX
DataBindings.Add( control property, data
source, data member)

control property       Property on the control that is being
                       bound.
data source            Object that contains data being
                       bound to control.
data member            Data member on the data source
                       that is being used. Set this to null if
                       the data source's ToString() method
                       provides the value.
MULTIPLE BINDINGS
A control may have multiple bindings
associated with it, but only one per
property.
This means that the code used to create
a binding can be executed only once; a
second attempt would generate an
exception.
Multiple Bindings
To avoid this, each call to add a binding should be
preceded with code that checks to see if a binding
already exists; if there is a binding, it should be
removed.


if (txtMovie.DataBindings["Text"] != null)

    txtMovie.DataBindings.Remove(txtMovie.DataBindings["Text"]);

txtMovie.DataBindings.Add("Text", tp, "Tb_Text");
BINDING TO A LIST
Instead of binding to a single object, the
control can be bound to an array.
The control can still only display a single
movie title at a time, but we can scroll
through the array and display a different title
that corresponds to the current array item
selected.
USING THE BINDING MANAGER
The simple part

// ArrayList of TextParms objects
ArrayList 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 Textbox
txtMovie.DataBindings.Add("Text", tbList, "Tb_Text");
txtMovie.DataBindings.Add("BackColor", tbList, "Tb_Background");
txtMovie.DataBindings.Add("Width", tbList, "Tb_Width");
SIMPLE BINDING WITH ADO .NET

Binding to a table in a DataSet is
basically the same as binding to a list.


For example, the Text property of the
control is bound to the movie_Year
column in a DataTable.
Binding to a DataSet

ds = 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 table

txtYr.DataBindings.Add("Text", ds,"movies.movie_Year");
NOTE…
Although the control could be bound directly
to a DataTable, the recommended approach
is to bind the property to a DataSet and use
the DataTable name as a qualifier to specify
the column that provides the data.
This makes it clear which table the value is
coming from.
COMPLEX DATA BINDING WITH
LIST CONTROLS
Complex binding is only available on controls
that include properties to specify a data
source and data members on the data source.
This select group of controls is limited to the
ListBox, CheckedListBox, ComboBox,
DataGrid, and DataGridView.
ListBox bound to a DataSet

da.Fill(ds,"movies");

DataTable dt = ds.Tables[0];

// Minimum properties to bind listbox to a DataTable

listBox1.DataSource = ds;

listBox1.DisplayMember = "movies.movie_Title";
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 control's content.
• Although no Binding object is explicitly created, a
  DataBindings collection is created underneath
  and is accessible through code.
GROUPING WITH OTHER
CONTROLS

Bound list box control is often grouped with
other controls, such as a text box or label, in
order to display multiple values from a row of
data. When the controls are bound to the
same data source, scrolling through the list
box causes each control to display a value
from the same data row.
An example…
txtStudio.DataBindings.Add("Text", ds,"movies.studio");

txtYear.DataBindings.Add("Text", ds,"movies.movie_Year");
ONE-WAY AND TWO-WAY DATA
BINDING
Data bound to a control can be changed in two
ways:
• By updating the underlying data source
• By modifying the visible contents of the control.
Changes should be reflected in the associated
control or data in both cases.


This is called TWO-WAY Binding.
ONE-WAY BINDING

A 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”
Updating a Control Value
In the case where a control is bound to a property on an object, the
property 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; } }
Updating a property
If a control is bound to an object property, a change to the value of that
property is not automatically sent to the control.

Instead, the binding manager looks for an event named propertyChanged
on the data source

// Event to notify bound control that value has changed
public event EventHandler Movie_YearChanged;
// Property control is bound to year value
public int Movie_Year {
   set {
          myYear = value;
          // Notify bound control(s) of change
          if (Movie_YearChanged != null)
             Movie_YearChanged(this, EventArgs.Empty);
       }
   get { return myYear; }
}
ADDING OR DELETING AN ITEM
FROM THE DATA SOURCE
Controls that are bound to the source
using simple binding are updated
automatically; controls using complex
binding are not.
In the latter case, the update can be
forced by executing the Refresh method
of a CurrencyManager object
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.
BINDING MANAGERS SYNCHRONIZE
THE DATA SOURCE AND CONTROLS
COORDINATING THE TWO-WAY FLOW
OF DATA BETWEEN A DATA SOURCE AND
CONTROL
• Binding
// Create a binding manager object
BindingManagerBase mgr= binding.BindingManagerBase;
• CurrencyManager
    • Bindings
    • Count
    • Current
    • Position
    • PositionChanged
    • CurrentChanged
COORDINATING THE TWO-WAY FLOW
OF DATA BETWEEN A DATA SOURCE AND
CONTROL
• PropertyManager : This class, which also derives from
  BindingManagerBase, maps the properties on an object
  to properties on a bound control.
• BindingContext : A program's 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"];
Using the BindingManagerBase
                 to Navigate a list
// Bind listbox to a dataset.datatable
listBox1.DataSource = ds;

listBox1.DisplayMember = "movies.movie_Title";
// Bind to TextBox
txtStudio.DataBindings.Add("text", ds, "movies.studio");

// BindingManagerBase bmb has class-wide scope
bmb = this.BindingContext[ds, "movies"];

// Create delegate pointing to event handler
bmb.PositionChanged += new EventHandler(bmb_PositionChanged);
USING THE POSITIONCHANGED EVENT


The PositionChanged event is fired each time
the binding manager moves to a new position
in the list.
This could be triggered programmatically or
by the user clicking a row in the list box
control.
PositionChanged Event
private 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"]);
    }
}
A sample application . . .
THE DATAGRIDVIEW CLASS
WHAT IS IT?

With more than a hundred properties and
methods, the DataGridView is by far the most
complex Windows Forms control for
displaying data.
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.
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
BASIC DATAGRIDVIEW ELEMENTS
5 ELEMENTARY STEPS
1. Define column headers
2. Define style for data cells
3. Define style for column headers
4. Define user capabilities
5. Place data in grid (manually or using
   datasource)
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
USING A DATA SOURCE
// Turn this off so column names do not come from data
source
dataGridView1.AutoGenerateColumns = false;

// Specify table as data source
dataGridView1.DataSource = ds;   // Dataset
dataGridView1.DataMember = "movies"; // Table in dataset

// Tie the columns in the grid to column names in the data
table
dataGridView1.Columns[0].DataPropertyName = “movie_title";
dataGridView1.Columns[1].DataPropertyName = “movie_year";
dataGridView1.Columns[2].DataPropertyName = “studio";
AND ANOTHER SAMPLE APPLICATION . . .
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.
EXAMPLE


DataGridViewButtonCell aButton =
new DataGridViewButtonCell ();


and similarly for other 5 controls.
EVENTS

Just about every mouse and cursor
movement that can occur over a
DataGridView can be detected by one of
its events
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 cell
Cell 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 cell's area.

               CellPainting (6)           Raised when a cell is to be
                                          painted.
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.
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(object
sender, DataGridViewCellFormattingEventArgs e)

(6) public sealed delegate void DataGridViewCellPaintingEventHandler(object sender,
DataGridViewCellPaintingEventArgs e)

(7) public sealed delegate voidDataGridViewDataErrorEventHandler(object sender,
DataGridViewDataErrorEventArgs e)
SOME IMPORTANT EVENTS
1. 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 Cells
3. 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.
MASTER-DETAIL DATAGRIDVIEWS
Records in the master table have multiple
associated records in the detail table
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.
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.
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
SO WHAT’S COOL?


If a row in the grid cannot be
satisfied from cache, the application
must load the cache with the
necessary data from the original
data source
DATA BINDING VERSUS VIRTUAL MODE
VIRTUAL MODE EVENTS
These events are triggered only in virtual mode.
Event                                Description
NewRowsNeeded                        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.
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.
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.
THANK YOU FOR YOUR
PATIENCE 


Slides Prepared and presented by :   ARVIND KRISHNAA J
Ad

More Related Content

What's hot (20)

Assemblies
AssembliesAssemblies
Assemblies
Janas Khan
 
Exception Handling in VB.Net
Exception Handling in VB.NetException Handling in VB.Net
Exception Handling in VB.Net
rishisingh190
 
Entity Relationship Diagrams
Entity Relationship DiagramsEntity Relationship Diagrams
Entity Relationship Diagrams
sadique_ghitm
 
Ch 7 data binding
Ch 7 data bindingCh 7 data binding
Ch 7 data binding
Madhuri Kavade
 
Webservices
WebservicesWebservices
Webservices
Gerard Sylvester
 
Introduction To Dotnet
Introduction To DotnetIntroduction To Dotnet
Introduction To Dotnet
SAMIR BHOGAYTA
 
WSDL
WSDLWSDL
WSDL
Akshay Ballarpure
 
ADO .Net
ADO .Net ADO .Net
ADO .Net
DrSonali Vyas
 
Event Driven programming(ch1 and ch2).pdf
Event Driven programming(ch1 and ch2).pdfEvent Driven programming(ch1 and ch2).pdf
Event Driven programming(ch1 and ch2).pdf
AliEndris3
 
Web Services (SOAP, WSDL, UDDI)
Web Services (SOAP, WSDL, UDDI)Web Services (SOAP, WSDL, UDDI)
Web Services (SOAP, WSDL, UDDI)
Peter R. Egli
 
Introduction to .NET Framework
Introduction to .NET FrameworkIntroduction to .NET Framework
Introduction to .NET Framework
Raghuveer Guthikonda
 
Ado.Net Tutorial
Ado.Net TutorialAdo.Net Tutorial
Ado.Net Tutorial
prabhu rajendran
 
SQL Overview
SQL OverviewSQL Overview
SQL Overview
Stewart Rogers
 
OODM-object oriented data model
OODM-object oriented data modelOODM-object oriented data model
OODM-object oriented data model
AnilPokhrel7
 
Php
PhpPhp
Php
Ajaigururaj R
 
Mvc architecture
Mvc architectureMvc architecture
Mvc architecture
Surbhi Panhalkar
 
JavaScript - Chapter 12 - Document Object Model
  JavaScript - Chapter 12 - Document Object Model  JavaScript - Chapter 12 - Document Object Model
JavaScript - Chapter 12 - Document Object Model
WebStackAcademy
 
Asp.net state management
Asp.net state managementAsp.net state management
Asp.net state management
priya Nithya
 
Relational Database Management System
Relational Database Management SystemRelational Database Management System
Relational Database Management System
Mian Abdul Raheem
 
SQL Commands
SQL Commands SQL Commands
SQL Commands
Sachidananda M H
 

Viewers also liked (20)

Diving in the Flex Data Binding Waters
Diving in the Flex Data Binding WatersDiving in the Flex Data Binding Waters
Diving in the Flex Data Binding Waters
michael.labriola
 
Chowka bhara
Chowka bharaChowka bhara
Chowka bhara
Arvind Krishnaa
 
Treeview listview
Treeview listviewTreeview listview
Treeview listview
Amandeep Kaur
 
Active x
Active xActive x
Active x
Karthick Suresh
 
ASP.NET Web API
ASP.NET Web APIASP.NET Web API
ASP.NET Web API
habib_786
 
Wcf development
Wcf developmentWcf development
Wcf development
Binu Bhasuran
 
The ASP.NET Web API for Beginners
The ASP.NET Web API for BeginnersThe ASP.NET Web API for Beginners
The ASP.NET Web API for Beginners
Kevin Hazzard
 
Excellent rest using asp.net web api
Excellent rest using asp.net web apiExcellent rest using asp.net web api
Excellent rest using asp.net web api
Maurice De Beijer [MVP]
 
Overview of Rest Service and ASP.NET WEB API
Overview of Rest Service and ASP.NET WEB APIOverview of Rest Service and ASP.NET WEB API
Overview of Rest Service and ASP.NET WEB API
Pankaj Bajaj
 
WCF tutorial
WCF tutorialWCF tutorial
WCF tutorial
Abhi Arya
 
ASP.NET WEB API
ASP.NET WEB APIASP.NET WEB API
ASP.NET WEB API
Thang Chung
 
ASP.NET Mvc 4 web api
ASP.NET Mvc 4 web apiASP.NET Mvc 4 web api
ASP.NET Mvc 4 web api
Tiago Knoch
 
3-TIER ARCHITECTURE IN ASP.NET MVC
3-TIER ARCHITECTURE IN ASP.NET MVC3-TIER ARCHITECTURE IN ASP.NET MVC
3-TIER ARCHITECTURE IN ASP.NET MVC
Mohd Manzoor Ahmed
 
C# ASP.NET WEB API APPLICATION DEVELOPMENT
C# ASP.NET WEB API APPLICATION DEVELOPMENTC# ASP.NET WEB API APPLICATION DEVELOPMENT
C# ASP.NET WEB API APPLICATION DEVELOPMENT
Dr. Awase Khirni Syed
 
The HFA pMDI Patent Landscape: Minefield or Goldmine
The HFA pMDI Patent Landscape: Minefield or GoldmineThe HFA pMDI Patent Landscape: Minefield or Goldmine
The HFA pMDI Patent Landscape: Minefield or Goldmine
CambridgeIP Ltd
 
Sosialisasi peningkatan integritas batam 12 nov 1
Sosialisasi peningkatan integritas batam 12 nov 1Sosialisasi peningkatan integritas batam 12 nov 1
Sosialisasi peningkatan integritas batam 12 nov 1
Mohammad Subhan
 
Accelerating innovation and diffusion of renewable energy technologies: techn...
Accelerating innovation and diffusion of renewable energy technologies: techn...Accelerating innovation and diffusion of renewable energy technologies: techn...
Accelerating innovation and diffusion of renewable energy technologies: techn...
CambridgeIP Ltd
 
Acacia Home and Garden
Acacia Home and GardenAcacia Home and Garden
Acacia Home and Garden
Jonathan Lucero
 
Ota sosiaalinen media tehokäyttöön
Ota sosiaalinen media tehokäyttöönOta sosiaalinen media tehokäyttöön
Ota sosiaalinen media tehokäyttöön
Darwin Oy
 
Diving in the Flex Data Binding Waters
Diving in the Flex Data Binding WatersDiving in the Flex Data Binding Waters
Diving in the Flex Data Binding Waters
michael.labriola
 
ASP.NET Web API
ASP.NET Web APIASP.NET Web API
ASP.NET Web API
habib_786
 
The ASP.NET Web API for Beginners
The ASP.NET Web API for BeginnersThe ASP.NET Web API for Beginners
The ASP.NET Web API for Beginners
Kevin Hazzard
 
Overview of Rest Service and ASP.NET WEB API
Overview of Rest Service and ASP.NET WEB APIOverview of Rest Service and ASP.NET WEB API
Overview of Rest Service and ASP.NET WEB API
Pankaj Bajaj
 
WCF tutorial
WCF tutorialWCF tutorial
WCF tutorial
Abhi Arya
 
ASP.NET Mvc 4 web api
ASP.NET Mvc 4 web apiASP.NET Mvc 4 web api
ASP.NET Mvc 4 web api
Tiago Knoch
 
3-TIER ARCHITECTURE IN ASP.NET MVC
3-TIER ARCHITECTURE IN ASP.NET MVC3-TIER ARCHITECTURE IN ASP.NET MVC
3-TIER ARCHITECTURE IN ASP.NET MVC
Mohd Manzoor Ahmed
 
C# ASP.NET WEB API APPLICATION DEVELOPMENT
C# ASP.NET WEB API APPLICATION DEVELOPMENTC# ASP.NET WEB API APPLICATION DEVELOPMENT
C# ASP.NET WEB API APPLICATION DEVELOPMENT
Dr. Awase Khirni Syed
 
The HFA pMDI Patent Landscape: Minefield or Goldmine
The HFA pMDI Patent Landscape: Minefield or GoldmineThe HFA pMDI Patent Landscape: Minefield or Goldmine
The HFA pMDI Patent Landscape: Minefield or Goldmine
CambridgeIP Ltd
 
Sosialisasi peningkatan integritas batam 12 nov 1
Sosialisasi peningkatan integritas batam 12 nov 1Sosialisasi peningkatan integritas batam 12 nov 1
Sosialisasi peningkatan integritas batam 12 nov 1
Mohammad Subhan
 
Accelerating innovation and diffusion of renewable energy technologies: techn...
Accelerating innovation and diffusion of renewable energy technologies: techn...Accelerating innovation and diffusion of renewable energy technologies: techn...
Accelerating innovation and diffusion of renewable energy technologies: techn...
CambridgeIP Ltd
 
Ota sosiaalinen media tehokäyttöön
Ota sosiaalinen media tehokäyttöönOta sosiaalinen media tehokäyttöön
Ota sosiaalinen media tehokäyttöön
Darwin Oy
 
Ad

Similar to Data Binding and Data Grid View Classes (20)

Advance Webpage Devlopment .NET
Advance Webpage Devlopment .NETAdvance Webpage Devlopment .NET
Advance Webpage Devlopment .NET
PandeyABHISHEK1
 
Data Binding in Silverlight
Data Binding in SilverlightData Binding in Silverlight
Data Binding in Silverlight
Boulos Dib
 
Dev308
Dev308Dev308
Dev308
guest2130e
 
Databind in asp.net
Databind in asp.netDatabind in asp.net
Databind in asp.net
Sireesh K
 
Lesson 05 Data Binding in WPF
Lesson 05 Data Binding in WPFLesson 05 Data Binding in WPF
Lesson 05 Data Binding in WPF
Quang Nguyễn Bá
 
Data Binding for Xamarin Forms In-Depth
Data Binding for Xamarin Forms In-DepthData Binding for Xamarin Forms In-Depth
Data Binding for Xamarin Forms In-Depth
Alejandro Ruiz Varela
 
Detail view in distributed technologies
Detail view in distributed technologiesDetail view in distributed technologies
Detail view in distributed technologies
jamessakila
 
WPF DATA BINDING CHEATSHEET V1.1
WPF DATA BINDING CHEATSHEET V1.1WPF DATA BINDING CHEATSHEET V1.1
WPF DATA BINDING CHEATSHEET V1.1
Vikas Pandey
 
Introduction to XAML and its features
Introduction to XAML and its featuresIntroduction to XAML and its features
Introduction to XAML and its features
Abhishek Sur
 
KnockoutJS and MVVM
KnockoutJS and MVVMKnockoutJS and MVVM
KnockoutJS and MVVM
Manvendra Singh
 
Chapter 15
Chapter 15Chapter 15
Chapter 15
application developer
 
VISUAL BASIC .net data accesss vii
VISUAL BASIC .net data accesss viiVISUAL BASIC .net data accesss vii
VISUAL BASIC .net data accesss vii
argusacademy
 
The Magic of WPF & MVVM
The Magic of WPF & MVVMThe Magic of WPF & MVVM
The Magic of WPF & MVVM
Abhishek Sur
 
Flex3 data binding
Flex3 data bindingFlex3 data binding
Flex3 data binding
guestdf3003
 
Ado.net session02
Ado.net session02Ado.net session02
Ado.net session02
Niit Care
 
the .NET Framework. It provides the claf
the .NET Framework. It provides the clafthe .NET Framework. It provides the claf
the .NET Framework. It provides the claf
TesfahunMaru1
 
Cis266 final review
Cis266 final reviewCis266 final review
Cis266 final review
Randy Riness @ South Puget Sound Community College
 
GRID VIEW PPT
GRID VIEW PPTGRID VIEW PPT
GRID VIEW PPT
bon secours college for women,
 
Vb.net session 06
Vb.net session 06Vb.net session 06
Vb.net session 06
Niit Care
 
Knockoutjs databinding
Knockoutjs databindingKnockoutjs databinding
Knockoutjs databinding
Boulos Dib
 
Ad

More from Arvind Krishnaa (17)

Twitter Agreement Analysis
Twitter Agreement AnalysisTwitter Agreement Analysis
Twitter Agreement Analysis
Arvind Krishnaa
 
Analogical thinking
Analogical thinkingAnalogical thinking
Analogical thinking
Arvind Krishnaa
 
Recognition of unistroke gesture sequences
Recognition of unistroke gesture sequencesRecognition of unistroke gesture sequences
Recognition of unistroke gesture sequences
Arvind Krishnaa
 
Human Altruism and Cooperation
Human Altruism and CooperationHuman Altruism and Cooperation
Human Altruism and Cooperation
Arvind Krishnaa
 
Canscape
CanscapeCanscape
Canscape
Arvind Krishnaa
 
Final review presentation
Final review presentationFinal review presentation
Final review presentation
Arvind Krishnaa
 
Third review presentation
Third review presentationThird review presentation
Third review presentation
Arvind Krishnaa
 
Second review presentation
Second review presentationSecond review presentation
Second review presentation
Arvind Krishnaa
 
First review presentation
First review presentationFirst review presentation
First review presentation
Arvind Krishnaa
 
Zeroth review presentation - eBay Turmeric / SMC
Zeroth review presentation - eBay Turmeric / SMCZeroth review presentation - eBay Turmeric / SMC
Zeroth review presentation - eBay Turmeric / SMC
Arvind Krishnaa
 
Canvas Based Presentation tool - First Review
Canvas Based Presentation tool - First ReviewCanvas Based Presentation tool - First Review
Canvas Based Presentation tool - First Review
Arvind Krishnaa
 
Canvas Based Presentation - Zeroth Review
Canvas Based Presentation - Zeroth ReviewCanvas Based Presentation - Zeroth Review
Canvas Based Presentation - Zeroth Review
Arvind Krishnaa
 
Smart camera monitoring system
Smart camera monitoring systemSmart camera monitoring system
Smart camera monitoring system
Arvind Krishnaa
 
Marine Pollution
Marine PollutionMarine Pollution
Marine Pollution
Arvind Krishnaa
 
Unix Shell and System Boot Process
Unix Shell and System Boot ProcessUnix Shell and System Boot Process
Unix Shell and System Boot Process
Arvind Krishnaa
 
Multithreading Concepts
Multithreading ConceptsMultithreading Concepts
Multithreading Concepts
Arvind Krishnaa
 
Design and Analysis of Algorithms
Design and Analysis of AlgorithmsDesign and Analysis of Algorithms
Design and Analysis of Algorithms
Arvind Krishnaa
 
Twitter Agreement Analysis
Twitter Agreement AnalysisTwitter Agreement Analysis
Twitter Agreement Analysis
Arvind Krishnaa
 
Recognition of unistroke gesture sequences
Recognition of unistroke gesture sequencesRecognition of unistroke gesture sequences
Recognition of unistroke gesture sequences
Arvind Krishnaa
 
Human Altruism and Cooperation
Human Altruism and CooperationHuman Altruism and Cooperation
Human Altruism and Cooperation
Arvind Krishnaa
 
Final review presentation
Final review presentationFinal review presentation
Final review presentation
Arvind Krishnaa
 
Third review presentation
Third review presentationThird review presentation
Third review presentation
Arvind Krishnaa
 
Second review presentation
Second review presentationSecond review presentation
Second review presentation
Arvind Krishnaa
 
First review presentation
First review presentationFirst review presentation
First review presentation
Arvind Krishnaa
 
Zeroth review presentation - eBay Turmeric / SMC
Zeroth review presentation - eBay Turmeric / SMCZeroth review presentation - eBay Turmeric / SMC
Zeroth review presentation - eBay Turmeric / SMC
Arvind Krishnaa
 
Canvas Based Presentation tool - First Review
Canvas Based Presentation tool - First ReviewCanvas Based Presentation tool - First Review
Canvas Based Presentation tool - First Review
Arvind Krishnaa
 
Canvas Based Presentation - Zeroth Review
Canvas Based Presentation - Zeroth ReviewCanvas Based Presentation - Zeroth Review
Canvas Based Presentation - Zeroth Review
Arvind Krishnaa
 
Smart camera monitoring system
Smart camera monitoring systemSmart camera monitoring system
Smart camera monitoring system
Arvind Krishnaa
 
Unix Shell and System Boot Process
Unix Shell and System Boot ProcessUnix Shell and System Boot Process
Unix Shell and System Boot Process
Arvind Krishnaa
 
Design and Analysis of Algorithms
Design and Analysis of AlgorithmsDesign and Analysis of Algorithms
Design and Analysis of Algorithms
Arvind Krishnaa
 

Recently uploaded (20)

Module_2_Types_and_Approaches_of_Research (2).pptx
Module_2_Types_and_Approaches_of_Research (2).pptxModule_2_Types_and_Approaches_of_Research (2).pptx
Module_2_Types_and_Approaches_of_Research (2).pptx
drroxannekemp
 
Peer Assessment_ Unit 2 Skills Development for Live Performance - for Libby.docx
Peer Assessment_ Unit 2 Skills Development for Live Performance - for Libby.docxPeer Assessment_ Unit 2 Skills Development for Live Performance - for Libby.docx
Peer Assessment_ Unit 2 Skills Development for Live Performance - for Libby.docx
19lburrell
 
Myopathies (muscle disorders) for undergraduate
Myopathies (muscle disorders) for undergraduateMyopathies (muscle disorders) for undergraduate
Myopathies (muscle disorders) for undergraduate
Mohamed Rizk Khodair
 
Final Evaluation.docx...........................
Final Evaluation.docx...........................Final Evaluation.docx...........................
Final Evaluation.docx...........................
l1bbyburrell
 
BÀI TẬP BỔ TRỢ TIẾNG ANH 9 THEO ĐƠN VỊ BÀI HỌC - GLOBAL SUCCESS - CẢ NĂM (TỪ...
BÀI TẬP BỔ TRỢ TIẾNG ANH 9 THEO ĐƠN VỊ BÀI HỌC - GLOBAL SUCCESS - CẢ NĂM (TỪ...BÀI TẬP BỔ TRỢ TIẾNG ANH 9 THEO ĐƠN VỊ BÀI HỌC - GLOBAL SUCCESS - CẢ NĂM (TỪ...
BÀI TẬP BỔ TRỢ TIẾNG ANH 9 THEO ĐƠN VỊ BÀI HỌC - GLOBAL SUCCESS - CẢ NĂM (TỪ...
Nguyen Thanh Tu Collection
 
DEATH & ITS TYPES AND PHYSIOLOGICAL CHANGES IN BODY AFTER DEATH, PATIENT WILL...
DEATH & ITS TYPES AND PHYSIOLOGICAL CHANGES IN BODY AFTER DEATH, PATIENT WILL...DEATH & ITS TYPES AND PHYSIOLOGICAL CHANGES IN BODY AFTER DEATH, PATIENT WILL...
DEATH & ITS TYPES AND PHYSIOLOGICAL CHANGES IN BODY AFTER DEATH, PATIENT WILL...
PoojaSen20
 
How to Manage Amounts in Local Currency in Odoo 18 Purchase
How to Manage Amounts in Local Currency in Odoo 18 PurchaseHow to Manage Amounts in Local Currency in Odoo 18 Purchase
How to Manage Amounts in Local Currency in Odoo 18 Purchase
Celine George
 
Classification of mental disorder in 5th semester bsc. nursing and also used ...
Classification of mental disorder in 5th semester bsc. nursing and also used ...Classification of mental disorder in 5th semester bsc. nursing and also used ...
Classification of mental disorder in 5th semester bsc. nursing and also used ...
parmarjuli1412
 
MEDICAL BIOLOGY MCQS BY. DR NASIR MUSTAFA
MEDICAL BIOLOGY MCQS  BY. DR NASIR MUSTAFAMEDICAL BIOLOGY MCQS  BY. DR NASIR MUSTAFA
MEDICAL BIOLOGY MCQS BY. DR NASIR MUSTAFA
Dr. Nasir Mustafa
 
ANTI-VIRAL DRUGS unit 3 Pharmacology 3.pptx
ANTI-VIRAL DRUGS unit 3 Pharmacology 3.pptxANTI-VIRAL DRUGS unit 3 Pharmacology 3.pptx
ANTI-VIRAL DRUGS unit 3 Pharmacology 3.pptx
Mayuri Chavan
 
COPA Apprentice exam Questions and answers PDF
COPA Apprentice exam Questions and answers PDFCOPA Apprentice exam Questions and answers PDF
COPA Apprentice exam Questions and answers PDF
SONU HEETSON
 
Look Up, Look Down: Spotting Local History Everywhere
Look Up, Look Down: Spotting Local History EverywhereLook Up, Look Down: Spotting Local History Everywhere
Look Up, Look Down: Spotting Local History Everywhere
History of Stoke Newington
 
Mental Health Assessment in 5th semester bsc. nursing and also used in 2nd ye...
Mental Health Assessment in 5th semester bsc. nursing and also used in 2nd ye...Mental Health Assessment in 5th semester bsc. nursing and also used in 2nd ye...
Mental Health Assessment in 5th semester bsc. nursing and also used in 2nd ye...
parmarjuli1412
 
PUBH1000 Slides - Module 11: Governance for Health
PUBH1000 Slides - Module 11: Governance for HealthPUBH1000 Slides - Module 11: Governance for Health
PUBH1000 Slides - Module 11: Governance for Health
JonathanHallett4
 
antiquity of writing in ancient India- literary & archaeological evidence
antiquity of writing in ancient India- literary & archaeological evidenceantiquity of writing in ancient India- literary & archaeological evidence
antiquity of writing in ancient India- literary & archaeological evidence
PrachiSontakke5
 
CNS infections (encephalitis, meningitis & Brain abscess
CNS infections (encephalitis, meningitis & Brain abscessCNS infections (encephalitis, meningitis & Brain abscess
CNS infections (encephalitis, meningitis & Brain abscess
Mohamed Rizk Khodair
 
Rebuilding the library community in a post-Twitter world
Rebuilding the library community in a post-Twitter worldRebuilding the library community in a post-Twitter world
Rebuilding the library community in a post-Twitter world
Ned Potter
 
Myasthenia gravis (Neuromuscular disorder)
Myasthenia gravis (Neuromuscular disorder)Myasthenia gravis (Neuromuscular disorder)
Myasthenia gravis (Neuromuscular disorder)
Mohamed Rizk Khodair
 
IPL QUIZ | THE QUIZ CLUB OF PSGCAS | 2025.pdf
IPL QUIZ | THE QUIZ CLUB OF PSGCAS | 2025.pdfIPL QUIZ | THE QUIZ CLUB OF PSGCAS | 2025.pdf
IPL QUIZ | THE QUIZ CLUB OF PSGCAS | 2025.pdf
Quiz Club of PSG College of Arts & Science
 
Module_2_Types_and_Approaches_of_Research (2).pptx
Module_2_Types_and_Approaches_of_Research (2).pptxModule_2_Types_and_Approaches_of_Research (2).pptx
Module_2_Types_and_Approaches_of_Research (2).pptx
drroxannekemp
 
Peer Assessment_ Unit 2 Skills Development for Live Performance - for Libby.docx
Peer Assessment_ Unit 2 Skills Development for Live Performance - for Libby.docxPeer Assessment_ Unit 2 Skills Development for Live Performance - for Libby.docx
Peer Assessment_ Unit 2 Skills Development for Live Performance - for Libby.docx
19lburrell
 
Myopathies (muscle disorders) for undergraduate
Myopathies (muscle disorders) for undergraduateMyopathies (muscle disorders) for undergraduate
Myopathies (muscle disorders) for undergraduate
Mohamed Rizk Khodair
 
Final Evaluation.docx...........................
Final Evaluation.docx...........................Final Evaluation.docx...........................
Final Evaluation.docx...........................
l1bbyburrell
 
BÀI TẬP BỔ TRỢ TIẾNG ANH 9 THEO ĐƠN VỊ BÀI HỌC - GLOBAL SUCCESS - CẢ NĂM (TỪ...
BÀI TẬP BỔ TRỢ TIẾNG ANH 9 THEO ĐƠN VỊ BÀI HỌC - GLOBAL SUCCESS - CẢ NĂM (TỪ...BÀI TẬP BỔ TRỢ TIẾNG ANH 9 THEO ĐƠN VỊ BÀI HỌC - GLOBAL SUCCESS - CẢ NĂM (TỪ...
BÀI TẬP BỔ TRỢ TIẾNG ANH 9 THEO ĐƠN VỊ BÀI HỌC - GLOBAL SUCCESS - CẢ NĂM (TỪ...
Nguyen Thanh Tu Collection
 
DEATH & ITS TYPES AND PHYSIOLOGICAL CHANGES IN BODY AFTER DEATH, PATIENT WILL...
DEATH & ITS TYPES AND PHYSIOLOGICAL CHANGES IN BODY AFTER DEATH, PATIENT WILL...DEATH & ITS TYPES AND PHYSIOLOGICAL CHANGES IN BODY AFTER DEATH, PATIENT WILL...
DEATH & ITS TYPES AND PHYSIOLOGICAL CHANGES IN BODY AFTER DEATH, PATIENT WILL...
PoojaSen20
 
How to Manage Amounts in Local Currency in Odoo 18 Purchase
How to Manage Amounts in Local Currency in Odoo 18 PurchaseHow to Manage Amounts in Local Currency in Odoo 18 Purchase
How to Manage Amounts in Local Currency in Odoo 18 Purchase
Celine George
 
Classification of mental disorder in 5th semester bsc. nursing and also used ...
Classification of mental disorder in 5th semester bsc. nursing and also used ...Classification of mental disorder in 5th semester bsc. nursing and also used ...
Classification of mental disorder in 5th semester bsc. nursing and also used ...
parmarjuli1412
 
MEDICAL BIOLOGY MCQS BY. DR NASIR MUSTAFA
MEDICAL BIOLOGY MCQS  BY. DR NASIR MUSTAFAMEDICAL BIOLOGY MCQS  BY. DR NASIR MUSTAFA
MEDICAL BIOLOGY MCQS BY. DR NASIR MUSTAFA
Dr. Nasir Mustafa
 
ANTI-VIRAL DRUGS unit 3 Pharmacology 3.pptx
ANTI-VIRAL DRUGS unit 3 Pharmacology 3.pptxANTI-VIRAL DRUGS unit 3 Pharmacology 3.pptx
ANTI-VIRAL DRUGS unit 3 Pharmacology 3.pptx
Mayuri Chavan
 
COPA Apprentice exam Questions and answers PDF
COPA Apprentice exam Questions and answers PDFCOPA Apprentice exam Questions and answers PDF
COPA Apprentice exam Questions and answers PDF
SONU HEETSON
 
Look Up, Look Down: Spotting Local History Everywhere
Look Up, Look Down: Spotting Local History EverywhereLook Up, Look Down: Spotting Local History Everywhere
Look Up, Look Down: Spotting Local History Everywhere
History of Stoke Newington
 
Mental Health Assessment in 5th semester bsc. nursing and also used in 2nd ye...
Mental Health Assessment in 5th semester bsc. nursing and also used in 2nd ye...Mental Health Assessment in 5th semester bsc. nursing and also used in 2nd ye...
Mental Health Assessment in 5th semester bsc. nursing and also used in 2nd ye...
parmarjuli1412
 
PUBH1000 Slides - Module 11: Governance for Health
PUBH1000 Slides - Module 11: Governance for HealthPUBH1000 Slides - Module 11: Governance for Health
PUBH1000 Slides - Module 11: Governance for Health
JonathanHallett4
 
antiquity of writing in ancient India- literary & archaeological evidence
antiquity of writing in ancient India- literary & archaeological evidenceantiquity of writing in ancient India- literary & archaeological evidence
antiquity of writing in ancient India- literary & archaeological evidence
PrachiSontakke5
 
CNS infections (encephalitis, meningitis & Brain abscess
CNS infections (encephalitis, meningitis & Brain abscessCNS infections (encephalitis, meningitis & Brain abscess
CNS infections (encephalitis, meningitis & Brain abscess
Mohamed Rizk Khodair
 
Rebuilding the library community in a post-Twitter world
Rebuilding the library community in a post-Twitter worldRebuilding the library community in a post-Twitter world
Rebuilding the library community in a post-Twitter world
Ned Potter
 
Myasthenia gravis (Neuromuscular disorder)
Myasthenia gravis (Neuromuscular disorder)Myasthenia gravis (Neuromuscular disorder)
Myasthenia gravis (Neuromuscular disorder)
Mohamed Rizk Khodair
 

Data Binding and Data Grid View Classes

  • 1. DATA BINDING AND DATA GRID VIEW CLASS A PRESENTATION BY Arvind Krishnaa J
  • 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. DATA BINDING Link the contents of a control with an underlying data source
  • 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. INTERMEDIATE DATA SOURCE The term intermediate data source is used to distinguish it from the original data source, which may be an external database
  • 6. IMPORTANT NOTE The controls cannot be bound directly to a data source over an active connection. Binding is restricted to the in- memory representation of the data.
  • 7. MULTIPLE CONTROLS BOUND TO A SINGLE DATA SOURCE
  • 8. SIMPLE DATA BINDING Simple data binding, which is available to all controls, links a data source to one or more properties of a control.
  • 9. DATA BINDING WITH A TEXTBOX An application can set properties of a textbox dynamically by binding them to a data source. The following program creates an object whose public properties are mapped to the properties on the TextBox
  • 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 control txtMovie.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. 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 properties accessing each data member
  • 12. DATA BINDING ADD METHOD The DataBindings.Add method creates a collection of bindings that links the data source to the control's properties.
  • 13. SYNTAX DataBindings.Add( control property, data source, data member) control property Property on the control that is being bound. data source Object that contains data being bound to control. data member Data member on the data source that is being used. Set this to null if the data source's ToString() method provides the value.
  • 14. MULTIPLE BINDINGS A control may have multiple bindings associated with it, but only one per property. This means that the code used to create a binding can be executed only once; a second attempt would generate an exception.
  • 15. Multiple Bindings To avoid this, each call to add a binding should be preceded with code that checks to see if a binding already exists; if there is a binding, it should be removed. if (txtMovie.DataBindings["Text"] != null) txtMovie.DataBindings.Remove(txtMovie.DataBindings["Text"]); txtMovie.DataBindings.Add("Text", tp, "Tb_Text");
  • 16. BINDING TO A LIST Instead of binding to a single object, the control can be bound to an array. The control can still only display a single movie title at a time, but we can scroll through the array and display a different title that corresponds to the current array item selected.
  • 17. USING THE BINDING MANAGER
  • 18. The simple part // ArrayList of TextParms objects ArrayList 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 Textbox txtMovie.DataBindings.Add("Text", tbList, "Tb_Text"); txtMovie.DataBindings.Add("BackColor", tbList, "Tb_Background"); txtMovie.DataBindings.Add("Width", tbList, "Tb_Width");
  • 19. SIMPLE BINDING WITH ADO .NET Binding to a table in a DataSet is basically the same as binding to a list. For example, the Text property of the control is bound to the movie_Year column in a DataTable.
  • 20. Binding to a DataSet ds = 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 table txtYr.DataBindings.Add("Text", ds,"movies.movie_Year");
  • 21. NOTE… Although the control could be bound directly to a DataTable, the recommended approach is to bind the property to a DataSet and use the DataTable name as a qualifier to specify the column that provides the data. This makes it clear which table the value is coming from.
  • 22. COMPLEX DATA BINDING WITH LIST CONTROLS Complex binding is only available on controls that include properties to specify a data source and data members on the data source. This select group of controls is limited to the ListBox, CheckedListBox, ComboBox, DataGrid, and DataGridView.
  • 23. ListBox bound to a DataSet da.Fill(ds,"movies"); DataTable dt = ds.Tables[0]; // Minimum properties to bind listbox to a DataTable listBox1.DataSource = ds; listBox1.DisplayMember = "movies.movie_Title";
  • 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 control's content. • Although no Binding object is explicitly created, a DataBindings collection is created underneath and is accessible through code.
  • 25. GROUPING WITH OTHER CONTROLS Bound list box control is often grouped with other controls, such as a text box or label, in order to display multiple values from a row of data. When the controls are bound to the same data source, scrolling through the list box causes each control to display a value from the same data row.
  • 27. ONE-WAY AND TWO-WAY DATA BINDING Data bound to a control can be changed in two ways: • By updating the underlying data source • By modifying the visible contents of the control. Changes should be reflected in the associated control or data in both cases. This is called TWO-WAY Binding.
  • 28. ONE-WAY BINDING A 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. Updating a Control Value In the case where a control is bound to a property on an object, the property 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. Updating a property If a control is bound to an object property, a change to the value of that property is not automatically sent to the control. Instead, the binding manager looks for an event named propertyChanged on the data source // Event to notify bound control that value has changed public event EventHandler Movie_YearChanged; // Property control is bound to year value public 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. ADDING OR DELETING AN ITEM FROM THE DATA SOURCE Controls that are bound to the source using simple binding are updated automatically; controls using complex binding are not. In the latter case, the update can be forced by executing the Refresh method of a CurrencyManager object
  • 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.
  • 33. BINDING MANAGERS SYNCHRONIZE THE DATA SOURCE AND CONTROLS
  • 34. COORDINATING THE TWO-WAY FLOW OF DATA BETWEEN A DATA SOURCE AND CONTROL • Binding // Create a binding manager object BindingManagerBase mgr= binding.BindingManagerBase; • CurrencyManager • Bindings • Count • Current • Position • PositionChanged • CurrentChanged
  • 35. COORDINATING THE TWO-WAY FLOW OF DATA BETWEEN A DATA SOURCE AND CONTROL • PropertyManager : This class, which also derives from BindingManagerBase, maps the properties on an object to properties on a bound control. • BindingContext : A program's 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. Using the BindingManagerBase to Navigate a list // Bind listbox to a dataset.datatable listBox1.DataSource = ds; listBox1.DisplayMember = "movies.movie_Title"; // Bind to TextBox txtStudio.DataBindings.Add("text", ds, "movies.studio"); // BindingManagerBase bmb has class-wide scope bmb = this.BindingContext[ds, "movies"]; // Create delegate pointing to event handler bmb.PositionChanged += new EventHandler(bmb_PositionChanged);
  • 37. USING THE POSITIONCHANGED EVENT The PositionChanged event is fired each time the binding manager moves to a new position in the list. This could be triggered programmatically or by the user clicking a row in the list box control.
  • 38. PositionChanged Event private 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"]); } }
  • 41. WHAT IS IT? With more than a hundred properties and methods, the DataGridView is by far the most complex Windows Forms control for displaying data.
  • 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. 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. 5 ELEMENTARY STEPS 1. Define column headers 2. Define style for data cells 3. Define style for column headers 4. Define user capabilities 5. Place data in grid (manually or using datasource)
  • 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. USING A DATA SOURCE // Turn this off so column names do not come from data source dataGridView1.AutoGenerateColumns = false; // Specify table as data source dataGridView1.DataSource = ds; // Dataset dataGridView1.DataMember = "movies"; // Table in dataset // Tie the columns in the grid to column names in the data table dataGridView1.Columns[0].DataPropertyName = “movie_title"; dataGridView1.Columns[1].DataPropertyName = “movie_year"; dataGridView1.Columns[2].DataPropertyName = “studio";
  • 48. AND ANOTHER SAMPLE APPLICATION . . .
  • 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. EXAMPLE DataGridViewButtonCell aButton = new DataGridViewButtonCell (); and similarly for other 5 controls.
  • 51. EVENTS Just about every mouse and cursor movement that can occur over a DataGridView can be detected by one of its events
  • 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 cell Cell 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 cell's area. CellPainting (6) Raised when a cell is to be painted.
  • 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. 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(object sender, DataGridViewCellFormattingEventArgs e) (6) public sealed delegate void DataGridViewCellPaintingEventHandler(object sender, DataGridViewCellPaintingEventArgs e) (7) public sealed delegate voidDataGridViewDataErrorEventHandler(object sender, DataGridViewDataErrorEventArgs e)
  • 55. SOME IMPORTANT EVENTS 1. 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 Cells 3. 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. MASTER-DETAIL DATAGRIDVIEWS Records in the master table have multiple associated records in the detail table
  • 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. 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. 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. SO WHAT’S COOL? If a row in the grid cannot be satisfied from cache, the application must load the cache with the necessary data from the original data source
  • 61. DATA BINDING VERSUS VIRTUAL MODE
  • 62. VIRTUAL MODE EVENTS These events are triggered only in virtual mode. Event Description NewRowsNeeded 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. 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. 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. THANK YOU FOR YOUR PATIENCE  Slides Prepared and presented by : ARVIND KRISHNAA J
  翻译: