You are here:About>Computing & Technology>Delphi Programming
About.comDelphi Programming
An Introduction to Data Binding in ASP.NET Applications
Learn how to add information to a Web Form, by binding controls to a source of data. Learn about data binding Web Controls for selecting choices (ListBox, DropDownList, RadioButtonList, CheckBoxList, etc). Find out about IEnumerable and IList .NET interfaces.
 Join the Discussion
"Post your views and comments to this chapter of the free Asp.Net Delphi Programming Course"
Discuss!
 Related Resources
• A Beginner's Guide to Asp.Net Programming for Delphi developers.TOC

Welcome to the nineteenth chapter of the FREE online programming course:
A Beginner's Guide to Asp.Net Programming for Delphi developers.
Data Binding Web Controls

Over the last few chapters we've introduced many of the Web Controls you use when creating dynamic web pages. The "data" we used was somehow static. For example, to populate a ListBox, we've added the items from code by using a predefined set of values.
Web Forms, as Windows forms do, allow displaying information by binding controls to a source of data - whatever that source of data is (database data, XML data, some array of values, etc.).

Throughout this chapter, you'll learn about the following:

  • What does data binding stand for in ASP.NET applications
  • The nature of "stateless" data binding
  • The DataBind method, and binding Web Controls for selecting choices
  • Data Binding
    Since Web Forms are stateless (all the information displayed on a Web Form gets *lost* between postbacks), data binding in Web Forms in somehow different from binding data in traditional Windows applications.
    We've all used to, for example, connect a TDBGrid control to a TDataSource control to display (and edit) data from some TDataSet control - in (Windows) Delphi database applications.

    Although data binding, as a term, is often related to displaying data from a database (using ADO.NET and/or BDP.NET), we'll first explore binding Web control using data not coming from some database. This way we'll focus on the core issues with ASP.NET data binding - working with databases will be covered in some future chapters.

    The Nature of ASP.NET data binding
    In Web Form applications, most of the data displayed to the user (visitor of the Web Site), is provided as read-only. For example, a search result page, in some online store, will display information about the searched products with optional links to a page with product details. The (search results) data can be retrieved from a database, with no need to enable users to enter data to be saved back to the database.

    With the above discussion in mind, here are some of the notes on Web Forms data binding:

    • ASP.NET data-binding architecture does not perform (automatic) updates - Web forms data binding is always read-only.
    • ASP.NET data binding is not limited to using ADO.NET (database) sources.
    • Data binding often requires using binding expressions directly in the aspx file. We'll discuss binding expressions in the next chapter.
    • While data biding provides control over what data is used for binding, when it is used and in what format, ASP.NET has the final word.
    • Data binding can be used to assign data values to a specific property of a control. Use the DataBindings entry in the Object Inspector at design time; use the DataBinding event at run time to data bind single-value controls at run time (again, this will be discussed in the coming chapters).
    • Multi-record controls (ListBox, DataList, Repeater, etc.) are bound to some DataSource to provide data for multiple items.
    The DataBind method and Data Bound Lists
    The simplest form of ASP.NET data binding is the automatic population of web controls, such as the ListBox, RadioButtonList, CheckBoxList, etc. Each of these controls inherits from a base ListControl class. The ListControl class defines a set of properties (and methods) used when doing data binding.
    What's more, any Web Control can be bound to some data source - since the overall ancestor of every Web Control is the Control class, and the Control class has the DataBind method. Data binding is in the heart of ASP.NET development.

    Note: the ListControl has a property named Items. This is a collection of ListItem objects. The ListItem class has the Text and Value properties. Text is the string value displayed in a list control, Value is an arbitrary (string) value associated with the item.
    Of course, we've already used ListItem objects. Here's a line of code to add an item to a ListBox control (named ListBox1):
    ListBox1.Items.Add(ListItem.Create('Text', 'Value'));

    Here's the set of common members of the ListControl class, related to data binding:

    • The DataSource property defines the source of data for the control. While DataSource is of the System.Object (TObject) type, an object must implement either the IEnumerable or IList interface to be used as the source of data for binding.
      When a control is "armed" with the IEnumerable interface, it provides iteration over a collection. Many of the classes in the .NET framework implement the IEnumerable interface: Array, ArraList, HashTable, DataReader, DataView, etc. Many of these classes implement the IList interface, too. The IList interface allows for a collection to be accessed by an index.
      With the above in mind, it is quite clear that data binding in ASP.NET is all but NOT strictly related to retrieving the information from some kind of database. A simple array of string values can be used as the DataSource.
    • The DataTextField property specifies the field (property) of the DataSource object to be used for the visible content of the control (the Text property of the underlying ListItem object).
    • The DataValueField property specifies the field (property) of the DataSource object to be used for the value content of the control - The Value property of the ListItem.
    • The DataTextFormating property enables specifying the .NET format string to be used when displaying the value for the DataTextField.
    • And finally, the DataBind method. DataBind is called to activate the binding after, at least, the DataSource has been provided.

    • When DataBind is executed for a control, it will call DataBind for all its child controls. What this means is that if you have several controls on a Web Forms page, you can call Page.DataBind for the Page! This will call DataBind for all the controls that have their DataSource property set.

    A real example
    Enough theory, let's see some code. Start up Delphi (like you haven't done that already), create a test ASP.NET application, and ...

    Drop a ListBox (ID = "FilesList") and a Label (ID = "FilesLabel") on a Web Form:

    Files example

    Add the following code in the Page_Load procedure:

    uses System.IO, ...
    
    procedure TwfDataBinding.Page_Load(
      sender: System.Object; 
      e: System.EventArgs);
    const
      rootFolder = 'c:\';
    var
      diRoot : DirectoryInfo;
      folders : array of DirectoryInfo;
    begin
      FileList.AutoPostBack := true;
    
      if (NOT Page.IsPostBack) then
      begin
        diRoot := DirectoryInfo.Create(rootFolder);
        folders := diRoot.GetDirectories;
    
        FileList.DataSource := folders;
        FileList.DataTextField := 'Name';
        FileList.DataValueField := 'FullName';
        FileList.DataTextFormatString := 'Folder: {0}';
        FileList.DataBind;
      end;
    end;
    

    Run the project .. the list box is populated with the name of the folders on disk C:.

    ListBox populated with folder names

    From the code above, the most common way of using the properties/methods we've discussed, is:

    1. Drop a ListControl descendant, such as a ListBox, on a Web Form
    2. Assign the DataSource property. In this example we are using an array of DirectoryInfo objects. The GetDirectories method of the DirectoryInfo class (defined in the System.IO namespace) returns the subdirectories of a specified path. Since the GetDirectories returns an array and arrays in .NET implement IEnumerable, the folders variable can be used as the DataSource for data binding.
    3. Define the DataTextField and DataValueField properties. This might sound tricky, yet is very straight forward. An element of the folders is an DirectoryInfo object. DirectoryInfo publishes Name and FullName properties (along with some others). Therefore, for the DataTextField and DataValueField we need to use the name of some property of the object we use to bind a specific item of the ListBox. Each item of the ListBox is binded with the DirectoryInfo object from the folders array; 'Name' property is used for display (DataTextField), 'FullName' is used for ListItem's Value property
    4. Call the DataBind method.

    Notice that the code is inside the if NOT Page.IsPostback block. You only need to fill the list once, since on each postback the data for the ListBox will be populated from the ViewState. Of course, if EnableViewState property of the ListBox would be set to false, we would have to run the code on each postback. What's more, since the data is held in the view state, after a few postbacks, it is possible that the data displayed to the user is not up-to-date (directories might have changed). If this is the case, you should add a "Refresh" button on a form and call DataBind for the ListBox to refresh the display.

    Note that we've set the AutoPostBack property of the ListBox to true, ensuring that once the user picks an item from the ListBox, the SelectedIndexChanged event for the ListBox gets fired:

    procedure TwfDataBinding.FileList_SelectedIndexChanged(
      sender: System.Object;
      e: System.EventArgs);
    var
      selectedFolder : string;
      filesInFolder : integer;
      fileInfos : array of FileInfo;
    begin
      selectedFolder := FileList.SelectedItem.Value;
      if not Directory.Exists(selectedFolder) then Exit;
      
      fileInfos := DirectoryInfo.Create(selectedFolder).GetFiles;
      filesInFolder := &Array(fileInfos).Length;
      FilesLabel.Text := 'Files in selected folder :' + 
                         filesInFolder.ToString;
    end;
    

    Using the ListBox's SelectedItem's Value property we write down (to the FilesLabel control) the number of the files in the selected folder. The FileInfo objects provide us with the information we need (the GetFiles method of the DirectoryInfo class retrieves an array of file names within a folder).

    Warning:
    1. You might get the "Access to the path "c:\??" is denied." exception. Of course, the example I provided is only intended to be used for learning purposes, you will NOT let the users "play" with the folder/file structure of a Web Server. The security (we are to discuss in some later chapters) built in ASP.NET will not let fooling around with the file system!

    2. Note that while the "DataTextField" is displayed in the list, the "DataValueField" is not. However if you look in the resulting HTML source of the page, you'll find full names of the folders listed in the control - another security issue here!
    Do not think that the data you set for the Value field is not visible to the users of your web application!

    To the next chapter: A Beginner's Guide to ASP.NET Programming for Delphi developers
    That's it for today. In the next chapter we'll continue exploring the topic of data binding in ASP.NET.

    If you need any kind of help at this point, please post to the Delphi Programming Forum where all the questions are answered and beginners are treated as experts.

    A Beginner's Guide to ASP.NET Programming for Delphi developers: Next Chapter >>
    >> Using Binding Expressions in Delphi ASP.NET Applications

    From Zarko Gajic,
    Your Guide to Delphi Programming.
    FREE Newsletter. Sign Up Now!
    Newsletters & RSSEmail to a friendSubmit to Digg
     All Topics | Email Article | | |
    Advertising Info | News & Events | Work at About | SiteMap | Reprints | HelpOur Story | Be a Guide
    User Agreement | Ethics Policy | Patent Info. | Privacy Policy©2008 About, Inc., A part of The New York Times Company. All rights reserved.