Binding Data in Web Forms

You've seen how to code your own DataSet and how to use the Dreamweaver MX MM:DataSetcustom tag to create a DataSet. All well and good, but the awesome part of ADO.NET and ASP.NET is that you have instant access to all data stored in the memory-resident DataSet. Moreover, you can bind almost any web control in a web form to a DataSet. Binding a web control to a DataSet means, among other things, you can automatically populate web controls. Imagine-you will never have to loop through a recordset again to incrementally populate a list box!

You can bind data to an ASP.NET page in two ways. The first method uses the DataSource property of server controls such as the Listbox, DropDownList, RadioButtonList, CheckboxList, Repeater, DataList, and DataGrid. The second uses a data-binding expression, which is commonly referred to as Dynamic Text. Dynamic Text can be used with or without a server control. Regardless of the method you employ, the actual binding of data to a control or a page requires the DataBind()command.

You can choose to bind data to the script page itself using ASP.NET:

Page.DataBind()

or you can choose to bind data to specific controls by naming the control in the DataBind()command

Listbox1.DataBind()

However, if you are not specifically binding data to a control, Dreamweaver MX offers you a custom tag alternative to the ASP.NET Page.DataBind() command-MM:PageBind. MM:PageBindallows you to insert the Dreamweaver MX custom tag instead of inserting ASP.NET code. To insert the MM:PageBind custom tag, take these steps:

  1. Activate the ASP.NET panel and choose the More Tags icon to open the Tag Chooser dialog box.

  2. Choose ASP.NET Tags and Macromedia Server Controls.

  3. Select MM:PageBind and click the Insert button to insert the custom tag in your script file. You can see an example of the MM:PageBind custom tag in Listing 15.3.

Now let's look at how to use a data-binding expression.

Data-Binding Expressions

You can use a data-binding expression, or Dynamic Text, anywhere in your script page. To do so you need only to insert an expression and the DataBind command into your ASP.NET page. As we mentioned, the DataBind command signals ASP.NET to bind data to controls in the script page. Let's demonstrate by using Dynamic Text to output the first value in the Category column of the DS DataSet. To do so, begin with the script page shown in Listing 15.3. As you recall, we've already created a DataSet of the tblCategories table. To bind Dynamic Text to the DataSet, follow these steps:

  1. Place your cursor between the Body tags of the script page.

  2. Choose Windows ® Server Behaviors to activate the Server Behaviors panel.

  3. Choose Panel ® Dynamic Text to open the Dynamic Text dialog box.

  4. Select the Category column from the Field list box, and click OK. Dreamweaver MX inserts the following line into your script page. You can see the script page in Listing 15.4 and the browser results in Figure 15.5.

    <%# DS.FieldValue("Category", Container) %>

    click to expand
    Figure 15.5: Dynamic Text result

Listing 15.4: DATABINDING_DYNAMICTEXT.ASPX

start example
<%@ Page Language="VB" ContentType="text/html" ResponseEncoding="iso-8859-1" %>  <%@ Register TagPrefix="MM" Namespace="DreamweaverCtrls" _  Assembly="DreamweaverCtrls,version=1.0.0.0,_  publicKeyToken=836f606ede05d46a,culture=neutral" %> <MM:DataSet runat="Server" IsStoredProcedure="false"  ConnectionString='<%# System.Configuration.ConfigurationSettings._  AppSettings("MM_CONNECTION_STRING_connnorbert") %>'  DatabaseType='<%# System.Configuration.ConfigurationSettings._  AppSettings("MM_CONNECTION_DATABASETYPE_connnorbert") %>'  CommandText='<%# "SELECT * FROM dbo.tblCategories" %>'  Debug="true" > </MM:DataSet>  <MM:PageBind runat="server" PostBackBind="true" /> <html> <head> <title>Data-bind Expression</title>  <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">  </head> <body> <%# DS.FieldValue("Category", Container) %> </body> </html> 
end example

Data-Binding through a Control's Data Source

Now let's take data-binding a step further. Using the same script page, let's bind the DataSet to a DropDownList control through the control's DataSource property. Doing so populates the display text of the control with all the values in the Category column. As well, we want to push the like values of the CategoryID column into the values of the DropDownList control. But, before we can add our DropDownList control, we must add a form control around the Dynamic Text in the script page using the following code:

<form runat=server>  </form>

Now, remove the Dynamic Text we previously placed in the script page and insert a DropDown- List control. To do so, follow these steps:

  1. Choose Insert ® ASP.NET Objects ® DropDownList to open the Tag Editor dialog box.

  2. Select the General category from the category list, and set the ID to DropDownList1.

  3. Select the Data category and insert the default DS DataSet view (<%# ds.defaultview %>) into the Data Source text field, insert Category into the Data Text Field, and insert CategoryID into the Data Value Field as shown in Figure 15.6.

    click to expand 

     
    click to expand
    Figure 15.6: The Tag Editor for a DropDownList. (top) The General category; (bottom) the Data category.

  4. Click OK to insert the following DropDownList code into your script file. Figure 15.7 shows the browser result.

    <asp:dropdownlist DataSource="<%# ds.defaultview %>" _  DataTextField="Category" DataValueField="Categoryid" _   runat="server"></asp:dropdownlist>

    click to expand
    Figure 15.7: Data bound DropDownList browser result

Data-Binding Web Server Controls

As we've shown, you can bind DataSets to many server controls through the DataSource property. However, three powerful data server controls in particular can alleviate a lot of development work: the Repeater, the DataList, and the DataGrid. They are a bit more complex than your standard server control. For that reason, you really need a bit of under-the-hood knowledge. Let's use Dreamweaver MX to create each data-bound server control and then examine them from a code perspective.

The Repeater Server Control

The Repeater server control loops through all records of the DataSet to display the information according to predefined templates. Templates are collections of server controls and HTML (Hypertext Markup Language) that allow you to specify the layout of the generated web page. You can use four types of templates with the Repeater server control:

  • ItemTemplate

  • AlternatingItemTemplate

  • HeaderTemplate and FooterTemplate

  • SeparatorTemplate

The ItemTemplate, which is the default, generates HTML for each row in the DataSet. The AlternatingItemTemplate generates a row for every other row of the DataSet. The AlternatingItemTemplate is generally used to offset the style of the ItemTemplate, for example, to generate alternating row colors. The HeaderTemplate and FooterTemplate generate HTML before and after the Repeater control generates content for the DataSet. The SeparatorTemplate generates content between each data row. This may sound complicated, but once you see it in action, you'll love this server control.

To add a Repeater server control to our script file, follow these steps:

  1. Remove the DropDownList box we created earlier.

  2. Insert another instance of Dynamic Text bound to the CategoryID column and an instance bound to the Category column of our DataSet.

  3. Add a <BR> tag.

  4. Select CategoryID, Category Dynamic Text, and <BR> tag.

  5. Activate the Server Behaviors panel and choose Repeat Region from the panel menu to open the Repeat Region dialog box, as shown in Figure 15.8.

    click to expand
    Figure 15.8: The Repeat Region dialog box

  6. Select the DS DataSet in the DataSet drop-down list box, and in the Show section, click the All Records option.

  7. When you click OK, Dreamweaver MX replaces the Dynamic Text code line with the following.

    <ASP:Repeater runat="server" DataSource='<%# DS.DefaultView %>'>   <ItemTemplate>    <%# DS.FieldValue("CategoryID", Container) %>  <%# DS.FieldValue("Category", Container) %><br>    </ItemTemplate>   </ASP:Repeater> 

This Repeater, while rather bare-bones, will output all the values in the CategoryID and Category columns of tblCategories. You can easily add templates to this code to make the display a bit more robust. Listing 15.5 shows the code for a more pleasing Repeater control for the Categories table of our Books database. Figure 15.9 shows the result in a browser. Let's briefly examine the code.

Listing 15.5: DW_REPEATER_EXTENDED.ASPX

start example
<%@ Page Language="VB" ContentType="text/html" ResponseEncoding="iso-8859-1" %>  <%@ Register TagPrefix="MM" Namespace="DreamweaverCtrls" _  Assembly="DreamweaverCtrls,version=1.0.0.0,_ publicKeyToken=836f606ede05d46a,culture=neutral" %>  <MM:DataSet runat="Server" IsStoredProcedure="false"  ConnectionString='<%# System.Configuration.ConfigurationSettings._  AppSettings("MM_CONNECTION_STRING_connnorbert") %>'  DatabaseType='<%# System.Configuration.ConfigurationSettings._  AppSettings("MM_CONNECTION_DATABASETYPE_connnorbert") %>'  CommandText='<%# "SELECT * FROM dbo.tblCategories" %>'  Debug="true" > </MM:DataSet>  <MM:PageBind runat="server" PostBackBind="true" /> <html> <head> <title>Repeater</title>  <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">  </head> <body> <form runat='server'>    <ASP:Repeater runat="server" DataSource='<%# DS.DefaultView %>'>     <HeaderTemplate>  <table width=400 cellspacing=0 cellpadding=2 border=0>   <tr>    <td><strong>CategoryID</strong></td>    <td><strong>Category</strong></td>   </tr>  <tr>  <td colspan=2><hr width="100%" size="1" noshade color="#003399"></td>  </tr>  </HeaderTemplate>     <ItemTemplate>  <tr>    <td><%# Container.DataItem("CategoryID") %></td>    <td><%# Container.DataItem("Category") %></td>  </tr>  </HeaderTemplate>     <AlternatingItemTemplate>  <tr>  <td bgcolor=#CCCCCC><%# Container.DataItem("CategoryID") %></td>  <td bgcolor=#CCCCCC><%# Container.DataItem("Category") %></td>  </tr>  </AlternatingItemTemplate> <FooterTemplate> </table>  </FooterTemplate>      </ASP:Repeater>  </form> </body> </html> 
end example

click to expand
Figure 15.9: The Repeater server control

As you can see in the code listing, we begin by establishing a data connection to the Books database. Then we register the Dreamweaver MX custom tags with the script page and use MM:DataSetto create our DS DataSet. Next we wrapped the Repeater server control around the Dynamic Text. As you can see, the Repeater server control consists of an opening and closing Repeater tag and the appropriate opening and closing Template tags. In our example, we created an HTML table with alternating background colors of the rows. To accomplish this, first we use the required ItemTemplate to create one standard formatted table row for each row in the DataSet.

<ASP:Repeater  runat="server" > <ItemTemplate>  <tr>    <td><%# Container.DataItem("CategoryID") %></td>    <td><%# Container.DataItem("Category") %></td>  </tr> </ItemTemplate> </ASP:Repeater> 

The next step is to create the alternating rows with a contrasting background color. To do so, we add the AlternatingItemTemplate to the Repeater tag content-making sure to set the table cell background color to gray (# CCCCCC).

<ASP:Repeater  runat="server" > <ItemTemplate>  <tr>    <td><%# Container.DataItem("CategoryID") %></td>    <td><%# Container.DataItem("Category") %></td>  </tr> </ItemTemplate> <AlternatingItemTemplate>  <tr>    <td bgcolor=#CCCCCC><%# Container.DataItem("CategoryID") %></td>    <td bgcolor=#CCCCCC><%# Container.DataItem("Category") %></td>  </tr> </AlternatingItemTemplate> </ASP:Repeater>

As you can probably guess, our code is missing the column headers identifying our data and the opening and closing Table tags. To add these to our Repeater control, use the HeaderTemplate and FooterTemplate.

<ASP:Repeater  runat="server" >  <HeaderTemplate>  <table width=400 cellspacing=0 cellpadding=2 border=0>  <tr>    <td><strong>CategoryID</strong></td>    <td><strong>Category</strong></td>  </tr>  <tr>    <td colspan=2><hr width="100%" size="1" noshade color="#003399"></td>  </tr>  </HeaderTemplate> <ItemTemplate>  <tr>    <td><%# Container.DataItem("CategoryID") %></td>    <td><%# Container.DataItem("Category") %></td>  </tr> </ItemTemplate> <AlternatingItemTemplate>  <tr>    <td bgcolor=#CCCCCC><%# Container.DataItem("CategoryID") %></td>    <td bgcolor=#CCCCCC><%# Container.DataItem("Category") %></td>  </tr>  </AlternatingItemTemplate> <FooterTemplate>  </table>  </FooterTemplate>  </ASP:Repeater>

Notice we did not include the SeparatorTemplate in our Repeater control. Because we utilized the AlternatingItemTemplate and displayed the Repeater data in an HTML table, the SeparatorTemplate was not necessary. However, if you would like to add it to the script file, the code would look something like the following:

<SeparatorTemplate>  <tr>    <td colspan=2><hr width="100%" size="1" noshade color="#003399"></td>  </tr> </SeparatorTemplate>

As you can see, ASP.NET makes use of a lot of templates in its server controls. Once you're comfortable with using templates with ASP.NET, you'll find that you write and reuse a lot of them. The perfect place to store your templates is in the Dreamweaver MX Library. Each template becomes a library item you can insert into your code at a moment's notice.

The DataList Server Control

You'll find the DataList server control similar to the Repeater server control, except for one important aspect. The DataList control allows users to interact and modify data presented in the control. Similar to the Repeater control, the DataList control loops through all records of the DataSet to display the information according to predefined templates. In addition to the four templates you are already aware of, the DataList server control supports the SelectedItemTemplate and EditItemTemplate. The SelectedItemTemplate generates a row of content only when the user selects an item from the DataList control. Typically, developers will change the presentation style of the row to identify the row currently selected. The EditItemTemplate generates a row of content when an item is put into edit mode. These templates work well to inform the user they have selected something or to empower the user to alter data.

To see how the DataList server control works, remove the Repeater control from our script file and then create the DataList server control. To do so, follow these steps:

  1. Choose Insert ® ASP.NET Objects ® DataList to open the DataList dialog box, as shown in Figure 15.10.You can also open this dialog box by activating the Application panel group and clicking the DataList icon.

    click to expand
    Figure 15.10: The DataList dialog box

    As you can see, the initial DataList dialog box includes far more property options than the Repeat Regions dialog box.

  2. To create our sample DataList, name the control DataList1, choose DS as the DataSet, and click the All Records option in the Show section.

    Warning 

    This Dreamweaver MX feature is misleading. You can choose to show a limited set of records, but doing so does not add the sorting functionality. It only sets attributes in the DataList control to trigger sorting functionality- which you must add on your own.

    Let's skip the Templates section for a moment.

  3. In the Organize Items section, select the Use Line Breaks option. (We'll be making a table of our own using DataList templates.)

  4. If you want DataList to create a table upon rendering, select the Use A Table option.

  5. Specify the number of columns. If you set the number of columns to greater than 1, be certain to set the Table Cell Fill Order accordingly. The Table Cell Fill Order option Wrap Top To Bottom displays items in the DataSet from top to bottom in each column you specify. Similarly, the Wrap Left To Right option displays items in the DataSet left to right. Now, you need to specify the properties in the Templates section. As you recall, DataList can use a Header, Item, AlternatingItem, EditItem, SelectedItem, Separator, and FooterTem- plate. The ItemTemplate is the only required template.

  6. In the Templates list, select Item.

  7. To insert a variable into the ItemTemplate Content text area that corresponds to the CategoryID or Category column in the DS DataSet, click the Add Data Field To Contents button to open the Add Data Field dialog box, as shown in Figure 15.11.

    click to expand
    Figure 15.11: Add DataField variables to the DataList Template Contents Area

  8. Choose CategoryID from the Data Field drop-down list, and then click OK.

  9. Choose Category from the Data Field drop-down list, and then click OK. As you can see in Figure 15.12, Dreamweaver MX inserts the appropriate variables into the Contents section of the DataList dialog box. All that's left for you to do is define more DataList templates and add the necessary formatting and functionality.

    click to expand
    Figure 15.12: Inserting template code in the DataList dialog box

  10. Click OK to insert the DataList control into our script page.

Listing 15.6 shows the Dreamweaver MX-generated code, and Figure 15.13 shows the DataList in Design mode.

Listing 15.6: DW_DATALIST.ASPX

start example
<%@ Page Language="VB" ContentType="text/html" ResponseEncoding="iso-8859-1" %>  <%@ Register TagPrefix="MM" Namespace="DreamweaverCtrls" _  Assembly="DreamweaverCtrls,version=1.0.0.0,_  publicKeyToken=836f606ede05d46a,culture=neutral" %> MM:DataSet runat="Server" IsStoredProcedure="false" ConnectionString='<%# System.Configuration.ConfigurationSettings._  AppSettings("MM_CONNECTION_STRING_connnorbert") %>'  DatabaseType='<%# System.Configuration.ConfigurationSettings_  AppSettings("MM_CONNECTION_DATABASETYPE_connnorbert") %>'  CommandText='<%# "SELECT * FROM dbo.tblCategories" %>'  Debug="true" > </MM:DataSet>  <MM:PageBind runat="server" PostBackBind="true" />             <html>  <head>  <title>Untitled Document</title>  <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">  </head> <body>     <form runat="server">      <asp:DataList  runat="server" RepeatColumns="1" RepeatDirection="Vertical"  RepeatLayout="Flow"  DataSource="<%# DS.DefaultView %>" >    <ItemTemplate>      <%# DS.FieldValue("CategoryID", Container) %>      <%# DS.FieldValue("Category", Container) %>    </ItemTemplate>  </asp:DataList>  </form> </body> </html> 
end example

click to expand
Figure 15.13: The DataList in Design mode

Building on the Dreamweaver Code

To further the formatting and functionality beyond the Dreamweaver MX basics, you can place HTML and ASP.NET code in the appropriate Template section. Listings 15.7 through 15.11 show sample template code.

The HeaderTemplate is used for the column headings of a table displaying data.

LISTING 15.7: THE HEADERTEMPLATE

start example
<table width=400 cellspacing=0 cellpadding=2 border=0>  <tr>    <td><strong>CategoryID</strong></td>    <td><strong>Category</strong></td>  </tr>  <tr>    <td colspan=2><hr width="100%" size="1" noshade color="#003399"></td>  </tr>
end example

The ItemTemplate is used to display a default view of the items in a DataSet.

Listing 15.8: THE ITEMTEMPLATE

start example
 <tr>    <td><asp:linkbutton  runat="server" commandname=Edit>_  <%# DS.FieldValue("CategoryID", Container) %></td>    <td><%# DS.FieldValue("Category", Container) %></td>  </tr>
end example

The AlternatingItemTemplate provides a different display for every other row of items in a DataSet. The alternate displays increase the readability of long tables of data.

Listing 15.9: THE ALTERNATINGITEMTEMPLATE

start example
 <tr>    <td bgcolor=#CCCCCC><asp:linkbutton  _  runat="server" commandname=Edit><%# DS.FieldValue("CategoryID", Container) %></td>    <td bgcolor=#CCCCCC><%# DS.FieldValue("Category", Container) %></td>  </tr>
end example

The EditItemTemplate provides a unique view to edit the items in the current row of the DataSet.

Listing 15.10: THE EDITITEMTEMPLATE

start example
<tr>  <td bgcolor=#CCCCCC>    <asp:LinkButton commandname="Cancel"  _  runat="server" text="Cancel" runat="server" />    <asp:LinkButton commandname="Update"  _  runat="server" text="Update" runat="server" />    <asp:LinkButton commandname="Delete"  _  runat="server" text="Delete" runat="server" />    </td>    <td bgcolor=#CCCCCC><asp:TextBox  runat="server" _  Text='<%# Container.DataItem("Category") %>' />       <asp:TextBox  ReadOnly="true" _  runat="server" Text='<%# Container.DataItem("CategoryID") %>' />  </td>  </tr> 
end example

The FooterTemplate provides a specialized display for the bottom of the DataList.

Listing 15.11: THE FOOTERTEMPLATE

start example
</table> 
end example

Keep in mind that to add true functionality to your DataList, you will also have to match the template code with events and procedures to accommodate templates that elicit actions such as the EditItemTemplate. Listing 15.12 shows a complete DataList script page ready for you to fill the event procedures with database functionality, and Figure 15.14 shows the results in a browser. Unfortunately, detailing the intricacies of custom scripting-server controls to dynamically update DataSets requires in-depth coverage of ASP.NET and is outside the range of this chapter. Don't let that stop you though. Check out http://msdn.microsoft.com/library/default.asp?url=/nhp/default.asp?contentid=28000440 to find out more about events and custom scripting.

Listing 15.12: DATALIST.ASPX

start example
<%@ Page Language="VB" ContentType="text/html" ResponseEncoding="iso-8859-1" %>  <%@ import Namespace="system.Data" %>  <%@ import Namespace="system.Data.OLE DB" %> <script runat="server">      'Create a DataConnection      Dim myConnection As OLE DBConnection      Dim myDataAdapter As OLE DBDataAdapter      dim ds as DataSet      Dim dt As DataTable      Dim dr As DataRow          Sub Page_Load(Sender As Object, E As EventArgs)          myconnection = new OLE DBConnection("Provider=SQLOLE DB.1;_  Persist Security Info=False;User ID=SA;Password=superman;Initial _  Catalog=MDWMX_BOOKS;Data Source=192.168.1.100")          myDataAdapter = new OLE DBDataAdapter("Select *_  from tblCategories", myconnection)              ds = new DataSet()          myDataAdapter.Fill(ds,"tblCategories")          'select data view and bind          DataList1.DataSource = ds          DataList1.DataMember = "tblCategories"          DataList1.DataBind()        End Sub        Sub DataList1_ItemCommand(Sender As Object, E As DataListCommandEventArgs)       DataList1.SelectedIndex = e.Item.ItemIndex       DataList1.DataBind()    End Sub  Sub DataList1_EditCommand(Sender As Object, E As DataListCommandEventArgs)      DataList1.EditItemIndex = e.Item.ItemIndex      DataList1.DataBind()  End Sub      Sub DataList1_CancelCommand(Sender As Object, E As DataListCommandEventArgs)      DataList1.EditItemIndex = -1      DataList1.DataBind()  End Sub      Sub DataList1_UpdateCommand(Sender As Object, E As DataListCommandEventArgs)      Dim tbxCategory As TextBox = e.Item.FindControl("tbxCategory")      Dim tbxCategoryID As TextBox = e.Item.FindControl("tbxCategoryID")          Dim Category As String = tbxCategory.Text      Dim CategoryID As integer = tbxCategoryID.Text      End Sub      Sub DataList1_DeleteCommand(Sender As Object, E As DataListCommandEventArgs)      Dim tbxCategory As TextBox = e.Item.FindControl("tbxCategory")      Dim tbxCategoryID As TextBox = e.Item.FindControl("tbxCategoryID")          Dim Category As String = tbxCategory.Text      Dim CategoryID As integer = tbxCategoryID.Text      End Sub  </script>             <html>  <head>  <title>DataList Server Control</title>  <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">  </head> <body>     <form runat=server>     <ASP:DataList  repeatlayout="Table" runat="server"  onItemCommand="Datalist1_ItemCommand"  onEditCommand="Datalist1_EditCommand"  onUpdateCommand="Datalist1_UpdateCommand"  onCancelCommand="Datalist1_CancelCommand"  onDeleteCommand="Datalist1_Delete Command" DataKeyField= "CategoryID" >     <HeaderTemplate>  <table width=400 cellspacing=0 cellpadding=2 border=0>  <tr> <td><strong>CategoryID</strong></td>  <td><strong>Category</strong></td>  </tr>  <tr>  <td colspan=2><hr width="100%" size="1"noshade color="#003399"></td>  </tr>  </HeaderTemplate>         <ItemTemplate>  <tr>      <td><asp:linkbutton  runat="server" _  commandname=Edit><%# Container.DataItem("CategoryID")     %></asp:linkbutton></td>      <td><%# Container.DataItem("Category") %></td>  </tr>  </ItemTemplate>     <SelectedItemTemplate>  <tr>      <td bgcolor=#CCCCCC><%# Container.DataItem("CategoryID") %></td>      <td bgcolor=#CCCCCC><%# Container.DataItem("Category") %></td>  </tr>  </SelectedItemTemplate>     <AlternatingItemTemplate>  <tr>          <td bgcolor=#CCCCCC><asp:linkbutton  _  runat="server" commandname=Edit><%#  Container.DataItem("CategoryID") %></asp:linkbutton></td>          <td bgcolor=#CCCCCC><%# Container.DataItem("Category") %></td>  </tr>  </AlternatingItemTemplate>             <EditItemTemplate>  <tr>       <td bgcolor=#CCCCCC>          <asp:LinkButton commandname="Cancel"  _  runat="server" text="Cancel" runat="server" />          <asp:LinkButton commandname="Update"  _  runat="server" text="Update" runat="server" />          <asp:LinkButton commandname="Delete"  _  runat="server" text="Delete" runat="server" />          </td>          <td bgcolor=#CCCCCC><asp:TextBox  runat="server" _  Text='<%# DataBinder.Eval(Container.DataItem, "Category") %>' />          <asp:TextBox  ReadOnly="true" runat="server" _  Text='<%# DataBinder.Eval(Container.DataItem, "CategoryID") %>' /> </td>   </tr>  </EditItemTemplate>             <FooterTemplate>  </table>  </FooterTemplate>  </ASP:DataList>  </form> </body> </html> 
end example

click to expand
Figure 15.14: : DataList.aspx

At the top of the script, DataList.aspx begins importing the required Data and OLE DB namespaces. It then establishes a data connection to the Books database, pulls data, and creates and fills a DataSet. Once the DataSet is filled, it is set as the data source to the DataList server control.

<%@ Page Language="VB" ContentType="text/html" ResponseEncoding="iso-8859-1" %>  <%@ import Namespace="system.Data" %>  <%@ import Namespace="system.Data.OLE DB" %> <script runat="server">          'Create a DataConnection          Dim myConnection As OLE DBConnection          Dim myDataAdapter As OLE DBDataAdapter          dim ds as DataSet          Dim dt As DataTable          Dim dr As DataRow              Sub Page_Load(Sender As Object, E As EventArgs)              myconnection = new OLE DBConnection("Provider=SQLOLE DB.1;_  Persist Security Info=False;User  ID=SA;Password=superman;Initial Catalog=MDWMX_BOOKS;Data  Source=192.168.1.100")              myDataAdapter = new OLE DBDataAdapter("Select *_  from tblCategories", myconnection)              ds = new DataSet()          myDataAdapter.Fill(ds,"tblCategories")          'select data view and bind          DataList1.DataSource = ds          DataList1.DataMember = "tblCategories"          DataList1.DataBind()      End Sub  

The next few procedures in DataList.aspx are event-driven. When the user selects an item to edit in the DataList server control or subsequently clicks a Cancel, Update, or Delete link, these special commands trigger an event that calls a function. These special commands can simply activate one of the DataList templates or execute custom code. For example, DataList1_ItemCommand activates the web content defined in the SelectedItemTemplate, and DataList1_EditCommand activates the web content in the EditItemTemplate. As you can see in Figure 15.14, DataList1_ItemCommand highlights the row a user clicks, and DataList1_EditCommand displays the form objects in the EditItemTemplate. DataList1_UpdateCommand, DataList1_CancelCommand, and DataList1_DeleteCommand are triggered when the user clicks similarly named links in the DataList. These commands typically run any custom database push-pull functionality you want to occur as the user manages the data in the DataSet.

Sub DataList1_ItemCommand(Sender As Object, E As DataListCommandEventArgs)      DataList1.SelectedIndex = e.Item.ItemIndex      DataList1.DataBind()  End Sub      Sub DataList1_EditCommand(Sender As Object, E As DataListCommandEventArgs)      DataList1.EditItemIndex = e.Item.ItemIndex      DataList1.DataBind()  End Sub      Sub DataList1_CancelCommand(Sender As Object, E As DataListCommandEventArgs)      DataList1.EditItemIndex = -1      DataList1.DataBind()  End Sub  Sub DataList1_UpdateCommand(Sender As Object, E As DataListCommandEventArgs)      Dim tbxCategory As TextBox = e.Item.FindControl("tbxCategory")      Dim tbxCategoryID As TextBox = e.Item.FindControl("tbxCategoryID")      Dim Category As String = tbxCategory.Text      Dim CategoryID As integer = tbxCategoryID.Text  End Sub      Sub DataList1_DeleteCommand(Sender As Object, E As DataListCommandEventArgs)      Dim tbxCategory As TextBox = e.Item.FindControl("tbxCategory")      Dim tbxCategoryID As TextBox = e.Item.FindControl("tbxCategoryID")      Dim Category As String = tbxCategory.Text      Dim CategoryID As integer = tbxCategoryID.Text  End Sub   

The final, all-important section of the code is the DataList itself. As we've mentioned, the DataList is composed of the opening and closing DataList tags surrounding the Header, Item, SelectedItem, EditItem, and FooterTemplate tags. To add the event behaviors that react to the data and user interaction, we've placed trigger events in the opening DataList tag. Once you add trigger events to your DataList, you'll need to modify and commit the DataSet to your database. For more information about updating a DataSet through a DataList, go to http://samples.gotdotnet.com/quickstart/aspplus/default.aspx?url=%2fquickstart%2faspplus%2fdoc%2fwebdatabinding.aspx .

<ASP:DataList  repeatlayout="Table" runat="server"  onItemCommand="Datalist1_ItemCommand"  onEditCommand="Datalist1_EditCommand"  onUpdateCommand="Datalist1_UpdateCommand"  onCancelCommand="Datalist1_CancelCommand"  onDeleteCommand="Datalist1_DeleteCommand"  DataKeyField="CategoryID" >

The DataGrid Server Control

The last, but most powerful, data-server control we're going to discuss is DataGrid. A DataGrid server control generates multicolumn tables from data sources such as a DataSet. You can format the columns in a variety of ways-data, button, hyperlink, templated, and so on. Using Dreamweaver MX to insert a DataGrid server control in a script page allows you to define an ASP.NET DataGrid server control from a dialog box interface.

The DataGrid server control is similar to both Repeater and DataList server controls. However, DataGrid provides much more functionality. DataGrid can generate a table column for each field in your DataSet or data source. DataGrid automatically chooses the best style to display data based on the data content. However, you can override the default column style and choose to display the column data in a variety of ways.

Bound The default column type. You can specify which columns to display, in what order, and you can specify how the columns display through styles.

Button Displays data as HTML buttons. This allows you to attach custom events and functionality to each piece of data.

Edit Displays data in form objects. This allows the end user to modify the data right from the display page.

Hyperlink Displays data in hyperlinks you define.

Template Just as with previous data-bound server controls, you can create custom templates to display data any way you wish.

The so very cool part of DataGrid is that you can use it as is to simply show the data in a data source. Alternatively, DataGrid has an enormous number of properties that you can use to modify to the nth degree.

Let's examine a DataGrid example. We'll create a simple DataGrid. To do so, follow these steps:

  1. Remove the DataList server control from the script page to make room for the DataGrid control.

  2. Choose Insert ® ASP.NET Objects ® DataGrid to open the DataGrid dialog box, as shown in Figure 15.15.You can also open this dialog box by activating the Server Behaviors panel and choosing DataGrid from the panel menu.

    click to expand
    Figure 15.15: The DataGrid dialog box

  3. In the ID box, enter DataGrid1.

  4. In the DataSet drop-down list box, select ds.

  5. In the Show section, click the All Records option.

  6. When you click OK, Dreamweaver MX inserts the DataGrid into your script page.

This simple implementation of DataGrid shown in Listing 15.13 and in Figure 15.16 automatically generates the columns and rows of our data source for us. As you can imagine, this example would take all of five minutes to use DataGrid to display the data in your data source.

Listing 15.13: DATAGRID_SIMPLE.ASPX

start example
<%@ Page Language="VB" ContentType="text/html" ResponseEncoding="iso-8859-1" %>  <%@ Register TagPrefix="MM" Namespace="DreamweaverCtrls" _  Assembly="DreamweaverCtrls,version=1.0.0.0,_  publicKeyToken=836f606ede05d46a,culture=neutral" %> <MM:DataSet runat="Server" IsStoredProcedure="false" ConnectionString='<%# System.Configuration.ConfigurationSettings._  AppSettings("MM_CONNECTION_STRING_connnorbert") %>'  DatabaseType='<%# System.Configuration.ConfigurationSettings._  AppSettings("MM_CONNECTION_DATABASETYPE_connnorbert") %>' CommandText='<%# "SELECT * FROM dbo.tblCategories" %>'  Debug="true" > </MM:DataSet>  <MM:PageBind runat="server" PostBackBind="true" /> <html> <head> <title>MMDataSet</title>  <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">  </head> <body>     <form runat="server">      <asp:DataGrid   runat="server"  AllowSorting="False"  AutoGenerateColumns="false"  CellPadding="3"  CellSpacing="0"  ShowFooter="false"  ShowHeader="true"  DataSource="<%# DS.DefaultView %>"  AllowPaging="false"  >    <HeaderStyle HorizontalAlign="center" BackColor="#E8EBFD"ForeColor="#3D3DB6"_  Font-Name="Verdana, Arial, Helvetica, sans-serif" _ Font-Bold="true" Font-Size="smaller" />    <ItemStyle BackColor="#F2F2F2" _  Font-Name="Verdana, Arial, Helvetica, sans-serif" _  Font-Size="smaller" />    <AlternatingItemStyle BackColor="#E5E5E5" _  Font-Name="Verdana, Arial, Helvetica, sans-serif" _  Font-Size="smaller" />    <FooterStyle HorizontalAlign="center" BackColor="#E8EBFD" _  ForeColor="#3D3DB6" Font-Name="Verdana, Arial, Helvetica, sans-serif" _  Font-Bold="true" Font-Size="smaller" />    <PagerStyle BackColor="white" _  Font-Name="Verdana, Arial, Helvetica, sans-serif" Font-Size="smaller" />  <Columns>   <asp:BoundColumn DataField="CategoryID"    HeaderText="CategoryID"    ReadOnly="true"    Visible="True"/>  <asp:BoundColumn DataField="Category"    HeaderText="Category"    ReadOnly="true"    Visible="True"/> </Columns>  </asp:DataGrid> </form> </body> </html>     
end example

click to expand
Figure 15.16: DataGrid_ simple.aspx

As you can see, a number of properties are defined in this DataGrid example. We'll discuss more about using the full potential of the DataGrid server control to delete and modify data in Chapter 21. Some are presentation styles; others, similar to DataList, are Edit, Update, and Cancel events and functions. DataGrid still has an enormous number of properties you can manipulate. You should investigate all DataGrid properties, as this is a tremendously powerful control that can save you hours of development time.

start sidebar
For Further Information

Individually, resources for ASP.NET, ADO.NET, and Dreamweaver MX are plentiful. However, precious few resources incorporate all three technologies. Some of our frequent haunts are www.gotdotnet.com/, http://msdn.microsoft.com/library/default.asp?url=/nhp/default.asp?contentid=28000440, and www.4guysfromrolla.com. A relatively new but fast favorite is www.udzone.com-a site to share and glean knowledge with the rest of the Dreamweaver MX community.

end sidebar



Mastering Dreamweaver MX Databases
Mastering Dreamweaver MX Databases
ISBN: 078214148X
EAN: 2147483647
Year: 2002
Pages: 214

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net