Chapter 8 Data Binding and Representation It is a capital mistake to theorize before one has data. Sir Arthur Conan Doyle,  The Adventures of Sherlock Holmes , “Scandal in Bohemia”
Overview This chapter examines  how data can be represented with the .NET Framework and how this data can be displayed using data binding in ASP.NET.  It covers: Data binding in ASP.NET Arrays Collection classes Generics DataTable and DataSet
Data Binding Almost every Web application displays data from some type of data source.  i.e., a typical Web page reads data from some external source, usually a database or an XML file, and presents it to the user.  Thus the developers of ASP.NET added a feature called  data binding  that facilitates displaying data from a data source in a control.
Data Binding Data binding refers to the process of dynamically assigning a value or values to a control at either design time or runtime and having the control automatically display the value or values.  That is, you only need tell the control where it can find its data, and the control handles the process of displaying it.
Data Binding Data binding a control to a data source can be achieved in one of two ways:  Setting the  DataSource  property of the control and then calling the  DataBind  method of the control. E.g., aControl.DataSource =  someDataSource ; aControl.DataBind(); Setting the  DataSourceId  property of the control to a data source control. The second approach was introduced in version 2.0 of ASP.NET and will be examined in the next chapter.
What Can Be a Data Source? The object that is to be assigned to the  DataSource  property of a bindable Web server control must be one that implements, either directly or indirectly, the  IEnumerable  or the  IListSource  interface.  These are: Arrays In-memory .NET collections classes, such as List and Dictionary ADO.NET  DbDataReader  objects ADO.NET  DataView ,  DataTable , or  DataSet  objects Any custom class you create, which also implements the  IEnumerable  interface
Data Binding an Array <asp:DropDownList id=&quot;drpSample&quot; runat=&quot;server&quot; /> private void Page_Load(object sender, System.EventArgs e) { string[] names = new string[3] { &quot;Austen&quot;,&quot;Dante&quot;,&quot;Goethe&quot; }; drpSample.DataSource = names; drpSample.DataBind(); }
Using Collections .NET Framework provides a number of  collection classes  that can also be used for data binding in fact, an array is just a special type of collection class.  A collection class is used to group related objects together.
Collection Classes There are a number of different types of collection classes.  There are queues, stacks, sorted and unsorted lists, and dictionaries.  Some of these collections can hold any type of object, whereas others are strongly typed. They provide members for adding, removing, and retrieving data elements.  All collections provide a mechanism that makes it easy to iterate through its elements.  Collections expand automatically as necessary.  There are also special  generic  versions of the collection classes that allow you to create strongly typed collections.
Collection Interfaces
Using the Collections Perhaps the two most commonly used by programmers are the  ArrayList  and  Hashtable  collections.  The  ArrayList  collection is ideal when: data needs to be principally accessed sequentially (that is, accessed from beginning to end)  speed of searching for an element is not too vital.  The  Hashtable  collection, by contrast, is optimized for quick nonsequential retrieval of elements via a key.
Using an ArrayList ArrayList myList = new ArrayList(); … Customer c1 = new Customer( … ); myList.Add( c1 ); int index = … Customer c = (Customer)myList[index]; // Create sample customer objects Customer c1 = new Customer(&quot;334&quot;, &quot;Thomas&quot;, &quot;Hobbes&quot;, &quot;123-4567&quot;); Customer c2 = new Customer(&quot;123&quot;, &quot;Jean-Jacques&quot;, &quot;Rosseau&quot;, &quot;456-1267&quot;); Customer c3 = new Customer(&quot;085&quot;, &quot;David&quot;, &quot;Hume&quot;, &quot;564-7823&quot;); // Create and populate collection ArrayList myList = new ArrayList(); myList.Add(c1); myList.Add(c2); myList.Add(c3); // Data bind collection to control lboxCustomers.DataSource = myList; lboxCustomers.DataBind();
Using an ArrayList <asp:ListBox id=&quot;lboxCustomers&quot; runat=&quot;server&quot;  DataTextField=&quot;Name&quot; DataValueField=&quot;Id&quot;  />
Problems with Standard Collection Classes Because all .NET classes have the  Object  class as their ultimate ancestor, this means that collections such as  ArrayList  and  Hashtable  can store and retrieve any .NET object.  Requires casting to appropriate type Thus there are some drawbacks: there is a potential for a casting exception if the data in the collection is not of the expected class. There is a performance penalty with the casting operation. In version 2.0 of the Framework there are now generic collections as a solution to these problems.
Generics Generics let you define a type-safe collection without maintenance or performance drawbacks.  They shift the burden of type-safety away from the developer and give it instead to the compiler.  This reduces the possibility of runtime errors and generally makes for cleaner code.  refers to the new capability in version 2.0 programming languages to support the use of placeholders rather than explicit type specifications when defining classes, structures, interfaces, or methods.  You can create your own generics as well as use any of the generic collection classes contained within the  System.Collections.Generics  namespace
Using Generics List<int> numbers = new List<int>(); List<Customer> customers = new List<Customer>(); numbers.Add(47); customers.Add( new Customer(&quot;085&quot;,&quot;David&quot;,&quot;Hume&quot;,&quot;564-7823&quot;) ); int n = numbers[0]; Customer c = customers[0];
Dictionary Collections With an  ArrayList  or  List  collection, you retrieve an individual element using its ordinal position within the collection.  There are times, however, when it is not convenient to retrieve an element by its position in the collection.  e.g., if you had a collection of  Customer  objects, it might be much more useful to retrieve a specific customer by using the customer name.  You can do so by using a dictionary-style collection such as  Dictionary  or  SortedDictionary  (or the older, nongeneric  Hashtable ).
Using a Dictionary Dictionary<string, Customer> dict = new Dictionary<string, Customer>(); String id = &quot;085&quot;; Customer c = new Customer(id, &quot;David&quot;, &quot;Hume&quot;, &quot;564-7823&quot;); dict.Add(id, c); … Customer c = dict[key];
Using a Dictionary List<Customer> myList = new List<Customer>(); … foreach (Customer c in myList) { if (c.Id == valueToFind) { // Do something with this customer } } Dictionary<string, Customer> dict = new  Dictionary<string, Customer>(); Customer c = dict[valueToFind]; if (c != null) { // Do something with this customer }
Iterating a Dictionary Dictionary<string, Customer> dict =  new Dictionary<string, Customer>(); // This does NOT work foreach (Customer c in dict) Dictionary<string, Customer> dict =  new Dictionary<string, Customer>(); // This does work foreach (Customer c in  dict.Values ) { labMsg.Text += c.Id + &quot;,&quot; + c.LastName + &quot;<br/>&quot;; }
DataSet The  DataSet  is a very rich and complete in-memory data container that mirrors the organization and some of the functionality of a DBMS.  That is, a  DataSet  is  an in-memory data holder that can store not only data, but also its relational structure,  can perform a variety of useful operations, such as  sorting and filtering data,  populating itself from XML,  exporting its data and schema to XML.
DataSet
Populating a DataSet There are three ways of populating a  DataSet  with data. Fill it from a database using the appropriate data provider’s  DataAdapter  class. Most common approach. Covered in next chapter. Programmatically add  DataTable  objects to the  DataSet .  Use the  ReadXml  method of the  DataSet  to populate data from an XML file or stream.
DataTable The heart of the  DataSet  is its collection of  DataTable  objects.  The  DataTable  class represents a single table of in-memory data, and can be used outside of the  DataSet .  Because,  the  DataSet  is such a complex class,  with Web applications you often need to only retrieve the data from a single table or query,  you often may want to work just with the  DataTable  as a general purpose data container and ignore its containing  DataSet .
Defining a DataTable DataTable table = new DataTable(); DataColumn firstNameCol = new DataColumn(&quot;FirstName&quot;, typeof(string)); table.Columns.Add(firstNameCol); DataColumn idCol = new DataColumn(); idCol.ColumnName = &quot;Id&quot;; idCol.DataType = typeof(Int32); idCol.AllowDBNull = false; idCol.Unique = true; table.Columns.Add(idCol);
Filling the DataTable DataRow r1 = table.NewRow(); r1[0] = 1; r1[1] = &quot;Thomas&quot;; r1[2] = &quot;Hobbes&quot;; r1[3] = &quot;123-4567&quot;; table.Rows.Add(r1); DataRow r2 = table.NewRow(); r2[&quot;Id&quot;] = 2; r2[&quot;FirstName&quot;] = &quot;David&quot;; r2[&quot;LastName&quot;] = &quot;Hume&quot;; r2[&quot;Phone&quot;] = &quot;564-7823&quot;; table.Rows.Add(r2);
Using a DataSet DataSet ds = new DataSet(); DataTable dt1 = new DataTable(); DataTable dt2 = new DataTable(); … ds.Tables.Add( dt1 ); ds.Tables.Add( dt2 ); DataTable t1 = ds.Tables[0]; DataTable t2 = ds.Tables[1]; ds.Tables[0].TableName = &quot;Cust&quot;; … DataTable dt = ds.Tables[&quot;Cust&quot;]; DataRow dr = ds.Tables[0].Rows[0]; string s1 = (string)dr[1]; string s2 = (string)dr[&quot;Phone&quot;]; string s3 = (string)ds.Tables[0].Rows[0][&quot;Phone&quot;];
Typed DataSets There is a way to achieve cleaner, type-safe code using the  DataSet  by using what is known as a typed  DataSet .  A typed  DataSet  is not a class within the .NET Framework.  Rather, it refers to a series of classes, the main of which inherits from  DataSet , that is generated by a special tool (usually you do this within Visual Studio).  These generated classes expose the data within a  DataSet  in a type-safe manner and allow for a more domain-oriented naming convention.  SampleTypedDataSet myDataSet = new SampleTypedDataSet(); … double price = myDataSet.Products[0].Price;
XML Integration try { DataSet ds = new DataSet(); ds.ReadXml( Server.MapPath(&quot;~/App_Data/somefile.xml&quot;) ); // Use the data set } catch (IOException) { // Handle the error } ds.WriteXml(&quot;output.xml&quot;);
Choosing a Data Container Because almost every ASP.NET application needs to work with data in some form or another, it is important to have some sense of the relative merits of the different ways in which you can store data programmatically.
Internal Data For most applications, data is external to the application.  That is, data is stored in some format, such as a database, an XML file, or a Web service, that is external to the application.  This external data also needs to be read in and manipulated and possibly stored internally within the application.
Storing Internal Data In this chapter, we have worked with the four main possibilities: .NET collections,  custom collections,  the DataSet (or just the DataTable),  the typed DataSet.
.NET Collections as Containers When used in conjunction with custom classes that represent entities in the business or application domain, the .NET collections, especially the generic versions, can be a particularly easy yet powerful way to organize the data used in your application.  They allow you to model the problem space of the application using the language of the problem domain, rather than the language of .NET.
.NET Collections as Containers The main drawback for these .NET collections is that these collections are general purpose.  That is, the functionality they provide is limited to the general behaviors of a collection, such as adding elements, retrieving elements, and removing elements.  You may have to write the code yourself for other behaviors, such as filling these collections from an external data source, searching for elements, sorting elements, or persisting the values back to the data source.
Custom Collections as Containers Custom collections along with custom entities allow you to create code that closely models the problem domain.  This tends to make the code more meaningful, and as some have argued creates a more maintainable and adaptable application.  This author prefers this approach, and in Chapter 11 we will explore it further.  The disadvantage to this approach is the necessity for implementing the extra functionality yourself.  As well, not every programmer is comfortable with the domain-focused, object-oriented development paradigm.  there are a variety of third-party code-generation or object-relational mapping tools that can help the developer that wants to use this domain-oriented approach.
DataSets as Containers Has a great deal of built-in functionality However,  the code necessary to manipulate individual items inside it is neither the most attractive, the most efficient, nor the most maintainable code possible.  The great power of the DataSet is often overkill for many scenarios, since most ASP.NET pages do not need a disconnected data container that caches multiple changes to the data.  If all we need is temporary storage for some data for the life of a request, all the extra memory used by the DataSet and its ancillary classes will have an effect on performance for no corresponding gain.  In fact, when retrieving data from a database, the DataSet can be several magnitudes of speed slower than other alternatives.
Typed DataSets as Containers A typed DataSet has all the advantages of the untyped DataSet.  As well, the typed DataSet provides a much simpler and easier object model than does the regular untyped DataSet.  However, they impose a database-centric approach to your application.  it can not contain any behaviors, such as business rules. the schema needs to be refreshed whenever the underlying data structure changes.

More Related Content

PDF
Html table tags
PDF
Python - object oriented
PPTX
HTML Forms
PPTX
Cascading Style Sheet (CSS)
ODP
CSS Basics
PPT
Css Ppt
PPTX
Array in c#
PPT
JavaScript Control Statements I
Html table tags
Python - object oriented
HTML Forms
Cascading Style Sheet (CSS)
CSS Basics
Css Ppt
Array in c#
JavaScript Control Statements I

What's hot (20)

PPTX
Android Layout.pptx
PPTX
Basic html structure
PPT
Javascript arrays
PDF
Generics
PPTX
Control Statements in Java
PPTX
Pandas csv
PDF
Python Tuple.pdf
ODP
Python Presentation
PPT
Document Object Model
PPT
ASP.NET MVC Presentation
PPTX
Css types internal, external and inline (1)
PPTX
OOP concepts -in-Python programming language
PPTX
HTML Tables
PPTX
PPTX
Event In JavaScript
PDF
Zero to Hero - Introduction to Python3
PPTX
Javascript functions
PPTX
Css Text Formatting
Android Layout.pptx
Basic html structure
Javascript arrays
Generics
Control Statements in Java
Pandas csv
Python Tuple.pdf
Python Presentation
Document Object Model
ASP.NET MVC Presentation
Css types internal, external and inline (1)
OOP concepts -in-Python programming language
HTML Tables
Event In JavaScript
Zero to Hero - Introduction to Python3
Javascript functions
Css Text Formatting
Ad

Viewers also liked (20)

PPT
Joyful Mysteries 2: Visitation
PDF
Haushalt 2015 Bergisch Gladbach - Entwurf
PPTX
La retórica en el lenguaje visual
PPTX
Miguel peña copia
PDF
B6 obtenção de matéria (parte ii)
PDF
A cabezazos contra el techo de cristal en #EBE15 Begoña Martínez y Beatriz Se...
PDF
1. cap1 farm general
PDF
Cook ijmbl 2010_preprint
PDF
Marketing News 04
TXT
Apache license
PPT
Presentación Lipo-Body Laser
PDF
Difusores de Gran Caudal de Aire y Conos de Alta Inducción - Serie DCH y CI
PDF
Ygj 02-adhesive-tape-roller
PDF
La inclusión es un verbo.
PPTX
Locsateli. Control y Gestion de flotas. Tracking fleet.
PDF
HAY - catalogue 2013 - 2nd edition
PPT
Smlatam Analysis V1
PPT
AISLAMIENTO ACÚSTICO EN VENTANAS
PPTX
Api presentation
Joyful Mysteries 2: Visitation
Haushalt 2015 Bergisch Gladbach - Entwurf
La retórica en el lenguaje visual
Miguel peña copia
B6 obtenção de matéria (parte ii)
A cabezazos contra el techo de cristal en #EBE15 Begoña Martínez y Beatriz Se...
1. cap1 farm general
Cook ijmbl 2010_preprint
Marketing News 04
Apache license
Presentación Lipo-Body Laser
Difusores de Gran Caudal de Aire y Conos de Alta Inducción - Serie DCH y CI
Ygj 02-adhesive-tape-roller
La inclusión es un verbo.
Locsateli. Control y Gestion de flotas. Tracking fleet.
HAY - catalogue 2013 - 2nd edition
Smlatam Analysis V1
AISLAMIENTO ACÚSTICO EN VENTANAS
Api presentation
Ad

Similar to ASP.NET 08 - Data Binding And Representation (20)

PPT
PostThis
PDF
Beginning linq
PPTX
2. overview of c#
PPTX
COLLECTIONS.pptx
PPTX
Linq Introduction
PPT
Generics collections
PPT
Generics Collections
PDF
C# Starter L04-Collections
PPTX
Linq Sanjay Vyas
PPT
Linq intro
PPT
Introduction to Linq
PPTX
CSharp for Unity - Day 1
PDF
ASP.Net 3.5 SP1 Dynamic Data
PPTX
Array list(1)
PPT
Language Integrated Query By Nyros Developer
PPT
Data Structure In C#
PPT
Understanding linq
PPTX
PPTX
PPT
PostThis
Beginning linq
2. overview of c#
COLLECTIONS.pptx
Linq Introduction
Generics collections
Generics Collections
C# Starter L04-Collections
Linq Sanjay Vyas
Linq intro
Introduction to Linq
CSharp for Unity - Day 1
ASP.Net 3.5 SP1 Dynamic Data
Array list(1)
Language Integrated Query By Nyros Developer
Data Structure In C#
Understanding linq

More from Randy Connolly (20)

PDF
Celebrating the Release of Computing Careers and Disciplines
PDF
Public Computing Intellectuals in the Age of AI Crisis
PDF
Why Computing Belongs Within the Social Sciences
PDF
Ten-Year Anniversary of our CIS Degree
PDF
Careers in Computing (2019 Edition)
PDF
Facing Backwards While Stumbling Forwards: The Future of Teaching Web Develop...
PDF
Where is the Internet? (2019 Edition)
PDF
Modern Web Development (2018)
PDF
Helping Prospective Students Understand the Computing Disciplines
PDF
Constructing a Web Development Textbook
PDF
Web Development for Managers
PDF
Disrupting the Discourse of the "Digital Disruption of _____"
PDF
17 Ways to Fail Your Courses
PDF
Red Fish Blue Fish: Reexamining Student Understanding of the Computing Discip...
PPTX
Constructing and revising a web development textbook
PDF
Computing is Not a Rock Band: Student Understanding of the Computing Disciplines
PDF
Citizenship: How do leaders in universities think about and experience citize...
PDF
Thinking About Technology
PDF
A longitudinal examination of SIGITE conference submission data
PDF
Web Security
Celebrating the Release of Computing Careers and Disciplines
Public Computing Intellectuals in the Age of AI Crisis
Why Computing Belongs Within the Social Sciences
Ten-Year Anniversary of our CIS Degree
Careers in Computing (2019 Edition)
Facing Backwards While Stumbling Forwards: The Future of Teaching Web Develop...
Where is the Internet? (2019 Edition)
Modern Web Development (2018)
Helping Prospective Students Understand the Computing Disciplines
Constructing a Web Development Textbook
Web Development for Managers
Disrupting the Discourse of the "Digital Disruption of _____"
17 Ways to Fail Your Courses
Red Fish Blue Fish: Reexamining Student Understanding of the Computing Discip...
Constructing and revising a web development textbook
Computing is Not a Rock Band: Student Understanding of the Computing Disciplines
Citizenship: How do leaders in universities think about and experience citize...
Thinking About Technology
A longitudinal examination of SIGITE conference submission data
Web Security

Recently uploaded (20)

PDF
NewMind AI Weekly Chronicles – August ’25 Week IV
PDF
Planning-an-Audit-A-How-To-Guide-Checklist-WP.pdf
PDF
Rapid Prototyping: A lecture on prototyping techniques for interface design
PDF
zbrain.ai-Scope Key Metrics Configuration and Best Practices.pdf
PPTX
Presentation - Principles of Instructional Design.pptx
PDF
The AI Revolution in Customer Service - 2025
PDF
Electrocardiogram sequences data analytics and classification using unsupervi...
PDF
Human Computer Interaction Miterm Lesson
PDF
CEH Module 2 Footprinting CEH V13, concepts
PDF
The-2025-Engineering-Revolution-AI-Quality-and-DevOps-Convergence.pdf
PDF
SaaS reusability assessment using machine learning techniques
PDF
substrate PowerPoint Presentation basic one
PDF
MENA-ECEONOMIC-CONTEXT-VC MENA-ECEONOMIC
PPTX
Module 1 Introduction to Web Programming .pptx
PDF
Transform-Quality-Engineering-with-AI-A-60-Day-Blueprint-for-Digital-Success.pdf
PDF
A hybrid framework for wild animal classification using fine-tuned DenseNet12...
PDF
Build Real-Time ML Apps with Python, Feast & NoSQL
PDF
Transform-Your-Streaming-Platform-with-AI-Driven-Quality-Engineering.pdf
PDF
Co-training pseudo-labeling for text classification with support vector machi...
PDF
“The Future of Visual AI: Efficient Multimodal Intelligence,” a Keynote Prese...
NewMind AI Weekly Chronicles – August ’25 Week IV
Planning-an-Audit-A-How-To-Guide-Checklist-WP.pdf
Rapid Prototyping: A lecture on prototyping techniques for interface design
zbrain.ai-Scope Key Metrics Configuration and Best Practices.pdf
Presentation - Principles of Instructional Design.pptx
The AI Revolution in Customer Service - 2025
Electrocardiogram sequences data analytics and classification using unsupervi...
Human Computer Interaction Miterm Lesson
CEH Module 2 Footprinting CEH V13, concepts
The-2025-Engineering-Revolution-AI-Quality-and-DevOps-Convergence.pdf
SaaS reusability assessment using machine learning techniques
substrate PowerPoint Presentation basic one
MENA-ECEONOMIC-CONTEXT-VC MENA-ECEONOMIC
Module 1 Introduction to Web Programming .pptx
Transform-Quality-Engineering-with-AI-A-60-Day-Blueprint-for-Digital-Success.pdf
A hybrid framework for wild animal classification using fine-tuned DenseNet12...
Build Real-Time ML Apps with Python, Feast & NoSQL
Transform-Your-Streaming-Platform-with-AI-Driven-Quality-Engineering.pdf
Co-training pseudo-labeling for text classification with support vector machi...
“The Future of Visual AI: Efficient Multimodal Intelligence,” a Keynote Prese...

ASP.NET 08 - Data Binding And Representation

  • 1. Chapter 8 Data Binding and Representation It is a capital mistake to theorize before one has data. Sir Arthur Conan Doyle, The Adventures of Sherlock Holmes , “Scandal in Bohemia”
  • 2. Overview This chapter examines how data can be represented with the .NET Framework and how this data can be displayed using data binding in ASP.NET. It covers: Data binding in ASP.NET Arrays Collection classes Generics DataTable and DataSet
  • 3. Data Binding Almost every Web application displays data from some type of data source. i.e., a typical Web page reads data from some external source, usually a database or an XML file, and presents it to the user. Thus the developers of ASP.NET added a feature called data binding that facilitates displaying data from a data source in a control.
  • 4. Data Binding Data binding refers to the process of dynamically assigning a value or values to a control at either design time or runtime and having the control automatically display the value or values. That is, you only need tell the control where it can find its data, and the control handles the process of displaying it.
  • 5. Data Binding Data binding a control to a data source can be achieved in one of two ways: Setting the DataSource property of the control and then calling the DataBind method of the control. E.g., aControl.DataSource = someDataSource ; aControl.DataBind(); Setting the DataSourceId property of the control to a data source control. The second approach was introduced in version 2.0 of ASP.NET and will be examined in the next chapter.
  • 6. What Can Be a Data Source? The object that is to be assigned to the DataSource property of a bindable Web server control must be one that implements, either directly or indirectly, the IEnumerable or the IListSource interface. These are: Arrays In-memory .NET collections classes, such as List and Dictionary ADO.NET DbDataReader objects ADO.NET DataView , DataTable , or DataSet objects Any custom class you create, which also implements the IEnumerable interface
  • 7. Data Binding an Array <asp:DropDownList id=&quot;drpSample&quot; runat=&quot;server&quot; /> private void Page_Load(object sender, System.EventArgs e) { string[] names = new string[3] { &quot;Austen&quot;,&quot;Dante&quot;,&quot;Goethe&quot; }; drpSample.DataSource = names; drpSample.DataBind(); }
  • 8. Using Collections .NET Framework provides a number of collection classes that can also be used for data binding in fact, an array is just a special type of collection class. A collection class is used to group related objects together.
  • 9. Collection Classes There are a number of different types of collection classes. There are queues, stacks, sorted and unsorted lists, and dictionaries. Some of these collections can hold any type of object, whereas others are strongly typed. They provide members for adding, removing, and retrieving data elements. All collections provide a mechanism that makes it easy to iterate through its elements. Collections expand automatically as necessary. There are also special generic versions of the collection classes that allow you to create strongly typed collections.
  • 11. Using the Collections Perhaps the two most commonly used by programmers are the ArrayList and Hashtable collections. The ArrayList collection is ideal when: data needs to be principally accessed sequentially (that is, accessed from beginning to end) speed of searching for an element is not too vital. The Hashtable collection, by contrast, is optimized for quick nonsequential retrieval of elements via a key.
  • 12. Using an ArrayList ArrayList myList = new ArrayList(); … Customer c1 = new Customer( … ); myList.Add( c1 ); int index = … Customer c = (Customer)myList[index]; // Create sample customer objects Customer c1 = new Customer(&quot;334&quot;, &quot;Thomas&quot;, &quot;Hobbes&quot;, &quot;123-4567&quot;); Customer c2 = new Customer(&quot;123&quot;, &quot;Jean-Jacques&quot;, &quot;Rosseau&quot;, &quot;456-1267&quot;); Customer c3 = new Customer(&quot;085&quot;, &quot;David&quot;, &quot;Hume&quot;, &quot;564-7823&quot;); // Create and populate collection ArrayList myList = new ArrayList(); myList.Add(c1); myList.Add(c2); myList.Add(c3); // Data bind collection to control lboxCustomers.DataSource = myList; lboxCustomers.DataBind();
  • 13. Using an ArrayList <asp:ListBox id=&quot;lboxCustomers&quot; runat=&quot;server&quot; DataTextField=&quot;Name&quot; DataValueField=&quot;Id&quot; />
  • 14. Problems with Standard Collection Classes Because all .NET classes have the Object class as their ultimate ancestor, this means that collections such as ArrayList and Hashtable can store and retrieve any .NET object. Requires casting to appropriate type Thus there are some drawbacks: there is a potential for a casting exception if the data in the collection is not of the expected class. There is a performance penalty with the casting operation. In version 2.0 of the Framework there are now generic collections as a solution to these problems.
  • 15. Generics Generics let you define a type-safe collection without maintenance or performance drawbacks. They shift the burden of type-safety away from the developer and give it instead to the compiler. This reduces the possibility of runtime errors and generally makes for cleaner code. refers to the new capability in version 2.0 programming languages to support the use of placeholders rather than explicit type specifications when defining classes, structures, interfaces, or methods. You can create your own generics as well as use any of the generic collection classes contained within the System.Collections.Generics namespace
  • 16. Using Generics List<int> numbers = new List<int>(); List<Customer> customers = new List<Customer>(); numbers.Add(47); customers.Add( new Customer(&quot;085&quot;,&quot;David&quot;,&quot;Hume&quot;,&quot;564-7823&quot;) ); int n = numbers[0]; Customer c = customers[0];
  • 17. Dictionary Collections With an ArrayList or List collection, you retrieve an individual element using its ordinal position within the collection. There are times, however, when it is not convenient to retrieve an element by its position in the collection. e.g., if you had a collection of Customer objects, it might be much more useful to retrieve a specific customer by using the customer name. You can do so by using a dictionary-style collection such as Dictionary or SortedDictionary (or the older, nongeneric Hashtable ).
  • 18. Using a Dictionary Dictionary<string, Customer> dict = new Dictionary<string, Customer>(); String id = &quot;085&quot;; Customer c = new Customer(id, &quot;David&quot;, &quot;Hume&quot;, &quot;564-7823&quot;); dict.Add(id, c); … Customer c = dict[key];
  • 19. Using a Dictionary List<Customer> myList = new List<Customer>(); … foreach (Customer c in myList) { if (c.Id == valueToFind) { // Do something with this customer } } Dictionary<string, Customer> dict = new Dictionary<string, Customer>(); Customer c = dict[valueToFind]; if (c != null) { // Do something with this customer }
  • 20. Iterating a Dictionary Dictionary<string, Customer> dict = new Dictionary<string, Customer>(); // This does NOT work foreach (Customer c in dict) Dictionary<string, Customer> dict = new Dictionary<string, Customer>(); // This does work foreach (Customer c in dict.Values ) { labMsg.Text += c.Id + &quot;,&quot; + c.LastName + &quot;<br/>&quot;; }
  • 21. DataSet The DataSet is a very rich and complete in-memory data container that mirrors the organization and some of the functionality of a DBMS. That is, a DataSet is an in-memory data holder that can store not only data, but also its relational structure, can perform a variety of useful operations, such as sorting and filtering data, populating itself from XML, exporting its data and schema to XML.
  • 23. Populating a DataSet There are three ways of populating a DataSet with data. Fill it from a database using the appropriate data provider’s DataAdapter class. Most common approach. Covered in next chapter. Programmatically add DataTable objects to the DataSet . Use the ReadXml method of the DataSet to populate data from an XML file or stream.
  • 24. DataTable The heart of the DataSet is its collection of DataTable objects. The DataTable class represents a single table of in-memory data, and can be used outside of the DataSet . Because, the DataSet is such a complex class, with Web applications you often need to only retrieve the data from a single table or query, you often may want to work just with the DataTable as a general purpose data container and ignore its containing DataSet .
  • 25. Defining a DataTable DataTable table = new DataTable(); DataColumn firstNameCol = new DataColumn(&quot;FirstName&quot;, typeof(string)); table.Columns.Add(firstNameCol); DataColumn idCol = new DataColumn(); idCol.ColumnName = &quot;Id&quot;; idCol.DataType = typeof(Int32); idCol.AllowDBNull = false; idCol.Unique = true; table.Columns.Add(idCol);
  • 26. Filling the DataTable DataRow r1 = table.NewRow(); r1[0] = 1; r1[1] = &quot;Thomas&quot;; r1[2] = &quot;Hobbes&quot;; r1[3] = &quot;123-4567&quot;; table.Rows.Add(r1); DataRow r2 = table.NewRow(); r2[&quot;Id&quot;] = 2; r2[&quot;FirstName&quot;] = &quot;David&quot;; r2[&quot;LastName&quot;] = &quot;Hume&quot;; r2[&quot;Phone&quot;] = &quot;564-7823&quot;; table.Rows.Add(r2);
  • 27. Using a DataSet DataSet ds = new DataSet(); DataTable dt1 = new DataTable(); DataTable dt2 = new DataTable(); … ds.Tables.Add( dt1 ); ds.Tables.Add( dt2 ); DataTable t1 = ds.Tables[0]; DataTable t2 = ds.Tables[1]; ds.Tables[0].TableName = &quot;Cust&quot;; … DataTable dt = ds.Tables[&quot;Cust&quot;]; DataRow dr = ds.Tables[0].Rows[0]; string s1 = (string)dr[1]; string s2 = (string)dr[&quot;Phone&quot;]; string s3 = (string)ds.Tables[0].Rows[0][&quot;Phone&quot;];
  • 28. Typed DataSets There is a way to achieve cleaner, type-safe code using the DataSet by using what is known as a typed DataSet . A typed DataSet is not a class within the .NET Framework. Rather, it refers to a series of classes, the main of which inherits from DataSet , that is generated by a special tool (usually you do this within Visual Studio). These generated classes expose the data within a DataSet in a type-safe manner and allow for a more domain-oriented naming convention. SampleTypedDataSet myDataSet = new SampleTypedDataSet(); … double price = myDataSet.Products[0].Price;
  • 29. XML Integration try { DataSet ds = new DataSet(); ds.ReadXml( Server.MapPath(&quot;~/App_Data/somefile.xml&quot;) ); // Use the data set } catch (IOException) { // Handle the error } ds.WriteXml(&quot;output.xml&quot;);
  • 30. Choosing a Data Container Because almost every ASP.NET application needs to work with data in some form or another, it is important to have some sense of the relative merits of the different ways in which you can store data programmatically.
  • 31. Internal Data For most applications, data is external to the application. That is, data is stored in some format, such as a database, an XML file, or a Web service, that is external to the application. This external data also needs to be read in and manipulated and possibly stored internally within the application.
  • 32. Storing Internal Data In this chapter, we have worked with the four main possibilities: .NET collections, custom collections, the DataSet (or just the DataTable), the typed DataSet.
  • 33. .NET Collections as Containers When used in conjunction with custom classes that represent entities in the business or application domain, the .NET collections, especially the generic versions, can be a particularly easy yet powerful way to organize the data used in your application. They allow you to model the problem space of the application using the language of the problem domain, rather than the language of .NET.
  • 34. .NET Collections as Containers The main drawback for these .NET collections is that these collections are general purpose. That is, the functionality they provide is limited to the general behaviors of a collection, such as adding elements, retrieving elements, and removing elements. You may have to write the code yourself for other behaviors, such as filling these collections from an external data source, searching for elements, sorting elements, or persisting the values back to the data source.
  • 35. Custom Collections as Containers Custom collections along with custom entities allow you to create code that closely models the problem domain. This tends to make the code more meaningful, and as some have argued creates a more maintainable and adaptable application. This author prefers this approach, and in Chapter 11 we will explore it further. The disadvantage to this approach is the necessity for implementing the extra functionality yourself. As well, not every programmer is comfortable with the domain-focused, object-oriented development paradigm. there are a variety of third-party code-generation or object-relational mapping tools that can help the developer that wants to use this domain-oriented approach.
  • 36. DataSets as Containers Has a great deal of built-in functionality However, the code necessary to manipulate individual items inside it is neither the most attractive, the most efficient, nor the most maintainable code possible. The great power of the DataSet is often overkill for many scenarios, since most ASP.NET pages do not need a disconnected data container that caches multiple changes to the data. If all we need is temporary storage for some data for the life of a request, all the extra memory used by the DataSet and its ancillary classes will have an effect on performance for no corresponding gain. In fact, when retrieving data from a database, the DataSet can be several magnitudes of speed slower than other alternatives.
  • 37. Typed DataSets as Containers A typed DataSet has all the advantages of the untyped DataSet. As well, the typed DataSet provides a much simpler and easier object model than does the regular untyped DataSet. However, they impose a database-centric approach to your application. it can not contain any behaviors, such as business rules. the schema needs to be refreshed whenever the underlying data structure changes.