ASP.NET Developer's Cookbook, Chapter 13

Page:   -1-    2    3    4    5    6    7    Next 

Chapter 13: Rendering Data with ASP.NET Web Controls

13.0. Introduction

ASP.NET provides several Web controls that make displaying data on a Web page easier than ever before. This chapter shows you how to take advantage of a process called data-binding to easily display data in a variety of formats using very little code. This chapter covers many of the most commonly used features of the Repeater, DataList, and DataGrid, including some fairly advanced DataGrid features. Using these data-bound Web controls, it is very easy to write data-driven Web Forms by just dragging and dropping a few controls onto a form and writing a few lines of code.

13.1. Rendering Data Directly on a Web Form

You want to display a piece of data on a Web Form using data-binding.

Technique

You can use the <%#%> syntax to easily bind data to a control. Simply create a variable, assign it a value, and call Page.DataBind to bind it to the page. The ASPX page is as follows:

<html>
 <body>
  <form id="Recipe1401vb" method="post" runat="server">
   <asp:Label ID="MyLabel" Runat="server">Hello <%#FirstName%>!
              </asp:Label>
  </form>
 </body>
</html>

In <script runat="server" /> block or codebehind:

Protected FirstName as string

Sub Page_Load(sender As Object, e As EventArgs)
  FirstName="Jeremy"
  Page.DataBind()
End Sub

Comments

If you are using codebehind, it is important to declare the variable with Protected access level so the page can access it. It is also important to realize that calling Page.DataBind() will result in all controls on the page being data-bound, because any time a control container calls its DataBind() method, it recursively calls the DataBind() method of all of its child controls.


See Also - Section 13.2, "Data-binding to a DropDownList"

Section 13.3, "Data-binding to a Repeater"

Section 13.4, "Data-binding to a DataList"

Section 13.7, "Data-binding to a DataGrid"


13.2. Data-binding to a DropDownList

You want to create a DropDownList that is populated from a database.

Technique

To data-bind a DropDownList to a data container such as a dataset or datareader, you must set three properties and call one method. The following example demonstrates this.

In <script runat="server" /> block or codebehind:

  Sub Page_Load(sender As Object, e As EventArgs)
    'object vars
    Dim sqlConnection As SqlConnection
    Dim sqlDataAdapter As SqlDataAdapter
    Dim sqlCommand As SqlCommand
    Dim dataSet As DataSet
   Dim dataTable As DataTable
   
    Try
      sqlConnection = New SqlConnection("Integrated Security=yes; _
                                       Initial Catalog=Northwind; _
                                       Data Source=(local)")
  
      'pass the stored proc name and SqlConnection
      sqlCommand = New SqlCommand("Select * From Customers", _
        sqlConnection)
  
      'instantiate SqlAdapter and DataSet
      sqlDataAdapter = New SqlDataAdapter(sqlCommand)
      dataSet = New DataSet()
  
      'populate the DataSet
      sqlDataAdapter.Fill(dataSet, "Customers")
  
     'apply sort to the DefaultView to sort by CompanyName
      dataSet.Tables(0).DefaultView.Sort = "CompanyName"
      
     DropDownList1.DataSource = _
                   dataSet.Tables("Customers").DefaultView
     DropDownList1.DataTextField = _
                   "CompanyName" ' what to display
     DropDownList1.DataValueField = _
                   "CustomerID" ' what to set as value
     DropDownList1.DataBind()
  
    Catch exception As Exception
      errorMsgLabel.Text = exception.ToString()
  
    End Try
  End Sub

Comments

As a general rule, you can perform this kind of data-binding only when the form first loads, as opposed to on every postback. To do this, simply place the data access and data-binding code within an If statement so that they are only performed when Page.IsPostback is false (for example, on the first load of the page). You can manipulate the Items collection after calling DataBind() if you need to set a particular item as Selected (use Items.FindByText or Items.FindByValue to find the item you want) or insert a default entry for the first item (use Items.Insert() with an index of 0 for the first item).


See Also - ASP.NET DropDownList I—http://aspalliance.com/stevesmith/articles/ dotnetlistbox1.asp

ASP.NET DropDownList II—http://aspalliance.com/stevesmith/articles/ dotnetlistbox2.asp

Dynamically Set Text and Value of DropDownList—http://aspalliance.com/aldotnet/ examples/dynamicdatasource.aspx


13.3. Data-binding to a Repeater

You want to use a repeater to output the results of a data query.

Technique

The Repeater control is the simplest of three templated data-bound controls provided with ASP.NET (the others being the DataList and DataGrid). It supports templates for Header, Item, AlternatingItem, Separator, and Footer, which can each contain static and dynamic (data-bound) content. The following example demonstrates how to set up a Repeater's templates and how to data-bind the Repeater to a dataset.

The ASPX page is as follows:

<asp:Repeater id="Repeater1" runat="server">
  <HeaderTemplate>Customers:<br/><ul></HeaderTemplate>
  <ItemTemplate>
   <li><%#DataBinder.Eval(Container.DataItem, "CompanyName")%>, 
     <%#DataBinder.Eval(Container.DataItem, "ContactName")%></li>
  </ItemTemplate>
  <AlternatingItemTemplate>
   <li><font color="red">
<%#DataBinder.Eval(Container.DataItem, "CompanyName")%>, 
<%#DataBinder.Eval(Container.DataItem, "ContactName")%></font></li>
  </AlternatingItemTemplate>
  <FooterTemplate><hr/>Data Retrieved at: 
<%# System.DateTime.Now.ToString() %></FooterTemplate>
</asp:Repeater>
       <br>
       <br>
       <asp:Label id="errorMsgLabel" runat="server" 
Width="327px" Height="111px"></asp:Label>

In <script runat="server" /> block or codebehind:

Sub BindRepeater()
  'object vars
  Dim sqlConnection As SqlConnection
  Dim sqlDataAdapter As SqlDataAdapter
  Dim sqlCommand As SqlCommand
  Dim dataSet As DataSet
  Dim dataTable As DataTable
  
  Try
    sqlConnection = New SqlConnection("Integrated Security=yes; _
                                      Initial Catalog=Northwind; _
                                      Data Source=(local)")

    'pass the stored proc name and SqlConnection
    sqlCommand = New SqlCommand("Select * From Customers", _
                                sqlConnection)

    'instantiate SqlAdapter and DataSet
    sqlDataAdapter = New SqlDataAdapter(sqlCommand)
    dataSet = New DataSet()

    'populate the DataSet
    sqlDataAdapter.Fill(dataSet, "Customers")

   'apply sort to the DefaultView to sort by CompanyName
    dataSet.Tables(0).DefaultView.Sort = "CompanyName"
    
    Repeater1.DataSource = dataSet.Tables("Customers").DefaultView
   Repeater1.DataBind()

  Catch exception As Exception
    errorMsgLabel.Text = exception.ToString()

  End Try
End Sub

Comments

BindRepeater() is called by Page_Load only when it is first loaded (not after a postback). It will automatically retain its state between postbacks using ViewState, thus avoiding additional requests to the database.


See Also - Repeater Class—http://msdn.microsoft.com/library/en-us/cpref/html/ frlrfsystemwebuiwebcontrolsrepeaterclasstopic.asp


Page:   -1-    2    3    4    5    6    7    Next 

From ASP.NET Developer's Cookbook by Steven A. Smith and Rob Howard published by Sams Publishing -- © Copyright Pearson Education. All rights reserved.



Comments

  • This article on database is very good and helpful.

    Posted by sagar141 on 05/03/2007 11:45am

    This article on database is very good and helpful.

    Reply
  • This article on database is very good and helpful.

    Posted by sagar141 on 05/03/2007 11:44am

    This article on database is very good and helpful.

    Reply
Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • Stories about devastating cyberattacks are plaguing the news. Why? The DNS protocol is easy to exploit. See your network the way hackers do—as an easy target. Learn how you can effectively secure your DNS infrastructure today.

  • Protecting business operations means shifting the priorities around availability from disaster recovery to business continuity. Enterprises are shifting their focus from recovery from a disaster to preventing the disaster in the first place. With this change in mindset, disaster recovery is no longer the first line of defense; the organizations with a smarter business continuity practice are less impacted when disasters strike. This SmartSelect will provide insight to help guide your enterprise toward better …

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds