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

  • Live Event Date: September 16, 2014 @ 11:00 a.m. ET / 8:00 a.m. PT Are you starting an on-premise-to-cloud data migration project? Have you thought about how much space you might need for your online platform or how to handle data that might be related to users who no longer exist? If these questions or any other concerns have been plaguing you about your migration project, check out this eSeminar. Join our speakers Betsy Bilhorn, VP, Product Management at Scribe, Mike Virnig, PowerSucess Manager and Michele …

  • As mobile devices have pushed their way into the enterprise, they have brought cloud apps along with them. This app explosion means account passwords are multiplying, which exposes corporate data and leads to help desk calls from frustrated users. This paper will discover how IT can improve user productivity, gain visibility and control over SaaS and mobile apps, and stop password sprawl. Download this white paper to learn: How you can leverage your existing AD to manage app access. Key capabilities to …

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds