List Controls

   

As with every other group of server controls, it pays for us to first take a look at the parent of all these controls. This group's Mama and Dada is the ListControl class, which is located in the System.Web.UI.WebControls namespace. Table 9.1 displays the ListControl's properties. It also has one method that the other list controls will inherit.

Table 9.1. ListControl Object Properties

Property

Description

AutoPostBack

Gets or sets a value indicating whether a postback to the server automatically occurs when the user changes the list selection.

DataMember

Gets or sets the specific table in the datasource to bind to the control.

DataSource

Gets or sets the data source that is used to populate the items of the list control.

DataTextField

Gets or sets what field in the data source provides the text content of the list items.

DataTextFormatString

Gets or sets the formatting string that controls the format of the data bound to the list control.

DataValueField

Gets or sets what field in the data source provides the value of each list item.

Items

Gets the collection of items in the list control.

SelectedIndex

Gets or sets the lowest index of the items selected in the list.

SelectedItem

Gets the item selected with the lowest index in the list control.

The event that I'd like to mention is the OnSelectedIndexChanged. The method is called whenever the selection of the list control changes and is posted back to the server. I'll show you a few examples in this section so that you understand it.

CheckBoxList

The CheckBoxList server control is an object that allows you to bind data to it; it dynamically generates a group of check boxes either in a table or just listed out, depending on how you want it to appear.

Note

Binding data is a concept that I haven't mentioned yet but is semi-self-explanatory. Each of the simple list controls, the repeater, and the complex list controls has a magical property called DataSource and a magical method called DataBind() that…well…binds data in the DataSource to the control.


Table 9.2 describes the CheckBoxList's properties.

Table 9.2. CheckBoxList Object Properties

Property

Description

CellPadding

Gets or sets the distance (in pixels) between the border and contents of the cell.

CellSpacing

Gets or sets the distance (in pixels) between cells.

RepeatColumns

Gets or sets how many columns to display in the CheckBoxList control.

RepeatDirection

Gets or sets a value that indicates whether the control displays vertically or horizontally. Values are Vertical or Horizontal. Vertical is default.

RepeatLayout

Gets or sets the layout of the check boxes. Flow or Table are valid; Table is the default. Flow displays items without table structure.

TextAlign

Gets or sets the text alignment for the check boxes within the group. Left or Right are valid; Right is the default.

Check out this control in action. I'm going to use a check box to change the RepeatDirection so I can control and set how this CheckBoxList is displayed in the browser.

Visual Basic .NET web_checkboxlist_vb.aspx
<%@ page language="vb" runat="server"%>  <script runat="server">  Sub Page_Load(sender as Object, e as EventArgs)      dim OurArray() as String = {"Item 1", "Item 2", "Item 3", "Item 4", "Item 5"}      if Not IsPostBack Then          OurCheckBoxList.DataSource = OurArray          DataBind()      end if  End Sub  Sub OurButton_Click(sender As Object, e As EventArgs)      Dim OurString As String = "You Selected:<br>"      Dim OurCounter As Integer      For OurCounter = 0 to OurCheckBoxList.Items.Count-1         If OurCheckBoxList.Items(OurCounter).Selected Then            OurString += OurCheckBoxList.Items(OurCounter).Text          OurString += "<br>"        End If     Next        OurLabel.Text = OurString  End Sub  Sub OurCheckBox_CheckedChanged(sender As Object, e As EventArgs)      If OurCheckBox.Checked Then          OurCheckBoxList.RepeatDirection = RepeatDirection.Vertical      Else          OurCheckBoxList.RepeatDirection = RepeatDirection.Horizontal      End If  End Sub  </script>  <html>  <head>  <title>Simple List Controls - CheckBoxList</title>  </head>  <body bgcolor="#FFFFFF" text="#000000">  <form runat="server">  <asp:CheckBoxList            BorderColor="#000000"      BorderWidth="1"      BackColor="#EEEEEE"      CellPadding="1"      CellSpacing="1"      runat="server" />  <br>  <asp:CheckBox            OnCheckedChanged="OurCheckBox_CheckedChanged"      Text="Display Vertically"      AutoPostBack="true"      Checked="True"      runat="server" />  <br>  <asp:Button  Text="Submit" onclick="OurButton_Click" runat="server"/>  <br><br>  <asp:Label  runat="server"/>  </form>  </body>  </html> 
C# web_checkboxlist_cs.aspx
<%@ page language="cs" runat="server"%>  <script runat="server">  void Page_Load(Object sender, EventArgs e) {     String[] OurArray = {"Item 1", "Item 2", "Item 3", "Item 4", "Item 5"};      if (!IsPostBack) {         OurCheckBoxList.DataSource = OurArray;          DataBind();      }  }  void OurButton_Click(Object sender, EventArgs e) {    String OurString = "You Selected:<br>";      int OurCounter;      for(OurCounter = 0; OurCounter < OurCheckBoxList.Items.Count; OurCounter++) {         if (OurCheckBoxList.Items[OurCounter].Selected) {            OurString = OurString + OurCheckBoxList.Items[OurCounter].Text;          OurString = OurString + "<br>";        }     }      OurLabel.Text = OurString;  }  void OurCheckBox_CheckedChanged(Object sender, EventArgs e) {     if (OurCheckBox.Checked) {         OurCheckBoxList.RepeatDirection = RepeatDirection.Vertical;      }      else {           OurCheckBoxList.RepeatDirection = RepeatDirection.Horizontal;      }  }  </script>  <html>  <head>  <title>Simple List Controls - CheckBoxList</title>  </head>  <body bgcolor="#FFFFFF" text="#000000">  <form runat="server">  <asp:CheckBoxList            BorderColor="#000000"      BorderWidth="1"      BackColor="#EEEEEE"      CellPadding="1"      CellSpacing="1"      runat="server" />  <br>  <asp:CheckBox            OnCheckedChanged="OurCheckBox_CheckedChanged"      Text="Display Vertically"      AutoPostBack="true"      Checked="True"      runat="server" />  <br>  <asp:Button  Text="Submit" onclick="OurButton_Click"  runat="server"/>  <br><br>  <asp:Label  runat="server"/>  </form>  </body>  </html> 

You can see the results of this ASP.NET page in Figure 9.1. This page changes the RepeatDirection property when the check box is checked and also inspects to see which items in the CheckBoxList are checked when the button is clicked.

Figure 9.1. The CheckBoxList enables you to easily create a collection of check boxes.
graphics/09fig01.gif

You can also see that the values were used in an array, and that this array was bound as the list's contents through its DataSource property and DataBind() method.

Notice that when the "Display Vertically" check box is changed, it calls a function called OurCheckBox_CheckedChanged. In this function the RepeatDirection property of the CheckBoxList is set with a strange value called either RepeatDirection.Vertical or RepeatDirection.Horizontal. The RepeatDirection property is really an integer as far as the .NET Framework is concerned. The Framework will only know what the words "Vertical" or "Horizontal" mean when they are associated with the proper property. So the .NET Framework actually sees RepeatDirection.Vertical or RepeatDirection.Horizontal as a number and not a String such as "Vertical" or "Horizontal".

DropDownList

I have snuck a few of these controls into this book to this point while demonstrating other aspects of ASP.NET. Now it's time to take a look at the DropDownList in more depth. It has only one additional property beyond what it inherits from the ListControl, as shown in Table 9.3.

Table 9.3. DropDownList Object Property

Property

Description

SelectedIndex

Gets or sets the index of the item selected in the DropDownList.

Visual Basic .NET web_dropdownlist_vb.aspx
<%@ page language="vb" runat="server"%>  <script runat=server>  Sub Page_Load(sender As Object, e As EventArgs)      if IsPostBack then          if OurDropDown.SelectedIndex = 0 then              OurLabel.Text = "This isn't a dessert"          Else              OurLabel.Text = "Text: " & OurDropDown.SelectedItem.Text & "<br>"              OurLabel.Text += "Value: " & OurDropDown.SelectedItem.Value & "<br>"              OurLabel.Text += "SelectedIndex: " & OurDropDown.SelectedIndex          end if      end if  end sub  </script>  <html>  <head>  <title>Simple List Controls - DropDownList</title>  </head>  <body bgcolor="#FFFFFF" text="#000000">  <form runat="server">  <asp:DropDownList            AutoPostBack="True"      runat="server">  <asp:ListItem value="" text="Pick your Favorite Dessert"/>  <asp:ListItem value="Cake's Value" text="Cake"/>  <asp:ListItem value="Cookies' Value" text="Cookies"/>  <asp:ListItem value="Ice Cream's Value" text="Ice Cream"/>  <asp:ListItem value="Pie's Value" text="Pie"/>  </asp:DropDownList>  <br>  <asp:label  runat="server" />  </form>  </body>  </html> 
C# web_dropdownlist_cs.aspx
<%@ page language="cs" runat="server"%>  <script runat=server>  void Page_Load(Object sender, EventArgs e){     if (IsPostBack){          if (OurDropDown.SelectedIndex == 0){              OurLabel.Text = "This isn't a dessert";          }else{              OurLabel.Text = "Text: " + OurDropDown.SelectedItem.Text + "<br>";              OurLabel.Text += "Value: " + OurDropDown.SelectedItem.Value + "<br>";              OurLabel.Text += "SelectedIndex: " + OurDropDown.SelectedIndex;          }      }  }  </script>  <html>  <head>  <title>Simple List Controls - DropDownList</title>  </head>  <body bgcolor="#FFFFFF" text="#000000">  <form runat="server">  <asp:DropDownList            AutoPostBack="True"      runat="server">  <asp:ListItem value="" text="Pick your Favorite Dessert"/>  <asp:ListItem value="Cake's Value" text="Cake"/>  <asp:ListItem value="Cookies' Value" text="Cookies"/>  <asp:ListItem value="Ice Cream's Value" text="Ice Cream"/>  <asp:ListItem value="Pie's Value" text="Pie"/>  </asp:DropDownList>  <br>  <asp:label  runat="server" />  </form>  </body>  </html> 

In Figure 9.2 you can see that the DropDownList posts back to the server whenever its value changes. Also notice that I used a different way of populating the DropDownList than I did with the CheckBoxList. This time I used a ListItem control, which will work with all simple list controls and will allow you to create items within the list individually.

Figure 9.2. The DropDownList allows you the programmatically control and access the <Select> input type as a single object.
graphics/09fig02.gif

Also notice that you can access not only the item's SelectedItems.Value, but you can also retrieve the SelectedItems.Text, as well, which is a beautiful thing. If you've ever had to try to get a drop-down box's text value before in traditional ASP, you know it was always quite a feat. Now it couldn't be simpler.

ListBox

The ListBox is pretty similar to the DropDownBox, with a few exceptions. First, ListBox can display multiple rows in the browser window, and second, it gives the user the ability to select multiple values from the ListBox. This multiple selection behavior parallels the behavior of the CheckBoxList, in that a user can select multiple values from the list control. Table 9.4 describes the two additional properties the ListBox has that make this possible.

Table 9.4. ListBox Object Properties

Property

Description

Rows

Gets or sets how many rows are to be displayed in the ListBox.

SelectionMode

Gets or sets the selection mode of the ListBox, either Single or Multiple. Default is Single.

The following example pulls data out of the Northwind database from the Categories table that can be seen in Figure 9.3. It sets the DataValueField property to the CategoryID column and the DataTextField to the CategoryName column. These will populate the <select> option's value property and populate the text property between the <option></option> tags, which will become the displayed text in the list box.

Figure 9.3. The Northwind database Categories table.
graphics/09fig03.gif
Visual Basic .NET web_listbox_vb.aspx
<%@ page language="vb" runat="server"%>  <%@ Import Namespace="System.Data"%>  <%@ Import Namespace="System.Data.SQLClient"%>  <script runat=server>  Sub Page_Load(sender As Object, e As EventArgs)      if IsPostBack then          if OurListBox.SelectedIndex > -1 then              dim i as Integer              for i = 0 to OurListBox.Items.Count - 1                  if OurListBox.Items(i).Selected Then                      OurText.Text += OurListBox.Items(i).Text & "<br>"                      OurValues.Text +=OurListBox.Items(i).Value & "<br>"                  end if              next              OurText.Text = "<u>Selected Text:</u><br> " & OurText.Text              OurValues.Text = "<u>Selected Values:</u><br> " & OurValues.Text          end if      else          DataSub      end if  end sub  Sub DataSub()      dim OurCommand as SQLCommand      dim OurConnection as SQLConnection      dim OurDataAdapter as SQLDataAdapter      dim OurDataSet as New DataSet()      OurConnection = New SQLConnection("Server=server;uid=newriders;pwd=password; graphics/ccc.gifdatabase=Northwind")      OurCommand = New SQLCommand("Select CategoryID,CategoryName from Categories", graphics/ccc.gifOurConnection)      OurDataAdapter = New SQLDataAdapter(OurCommand)      OurDataAdapter.Fill(OurDataSet, "Categories")      dim OurDataTable as New DataView(OurDataSet.Tables("Categories"))      OurListBox.DataSource = OurDataTable      OurListBox.DataBind()  End Sub  </script>  <html>  <head>  <title>Simple List Controls - ListBox</title>  </head>  <body bgcolor="#FFFFFF" text="#000000">  <form runat="server">  Please select the Categories you want.<br>  <asp:ListBox            DataTextField="CategoryName"      DataValueField="CategoryID"      Rows="6"      SelectionMode="Multiple"      runat="server" />  <asp:button text="Click Me" runat="server" />  <br><br>  <asp:label  EnableViewState="false" runat="server" /><br>  <asp:label  EnableViewState="false" runat="server" /><br>  </form>  </body>  </html> 
C# web_listbox_cs.aspx
<%@ page language="cs" runat="server"%>  <%@ Import Namespace="System.Data"%>  <%@ Import Namespace="System.Data.SqlClient"%>  <script runat=server>  void Page_Load(Object sender, EventArgs e) {     if (IsPostBack){         if (OurListBox.SelectedIndex > -1){              int i;              for (i = 0; i < OurListBox.Items.Count;i++){                  if (OurListBox.Items[i].Selected){                      OurText.Text += OurListBox.Items[i].Text + "<br>";                      OurValues.Text +=OurListBox.Items[i].Value + "<br>";                  }              }              OurText.Text = "<u>Selected Text:</u><br> " + OurText.Text;              OurValues.Text = "<u>Selected Values:</u><br> " + OurValues.Text;          }      }else{         DataSub();      }  }  void DataSub(){     SqlCommand OurCommand;      SqlConnection OurConnection;      SqlDataAdapter OurDataAdapter;      DataSet OurDataSet;      OurDataSet = new DataSet();      OurConnection = new  SqlConnection("Server=server;uid=newriders;pwd=password;database=Northwind");      OurCommand = new SqlCommand("Select CategoryID,CategoryName from Categories", graphics/ccc.gifOurConnection);      OurDataAdapter = new SqlDataAdapter(OurCommand);      OurDataAdapter.Fill(OurDataSet, "Categories");      DataView OurDataTable = new DataView(OurDataSet.Tables["Categories"]);      OurListBox.DataSource = OurDataTable;      OurListBox.DataBind();  }  </script>    <html>  <head>  <title>Simple List Controls - ListBox</title>  </head>  <body bgcolor="#FFFFFF" text="#000000">  <form runat="server">  Please select the Categories you want.<br>  <asp:ListBox            DataTextField="CategoryName"      DataValueField="CategoryID"      Rows="6"      SelectionMode="Multiple"      runat="server" />  <asp:button text="Click Me" runat="server" />  <br><br>  <asp:label  EnableViewState="false" runat="server" /><br>  <asp:label  EnableViewState="false" runat="server" /><br>  </form>  </body>  </html> 

You can see in Figure 9.4 how the ListBox enables a user to select multiple options from with the ListBox's options. If you look at the code examples, you can see that, as with the DropDownList, you can retrieve both the text and value properties of the ListBox.

Figure 9.4. The ListBox server control gives you a tool that enables the user to select multiple options from a list of items.
graphics/09fig04.gif

RadioButtonList

If the ListBox and the CheckBoxList behave similarly in allowing multiple selections from their respective lists, the RadioButtonList is similar to the DropDownList in that they both allow only a single selection from their lists. In the appearance arena, the RadioButtonList acts similarly to the CheckBoxList in that it has all the same additional properties. It can be displayed either in a table or inline, and you can control how the list repeats itself, as well.

Table 9.5. RadioButtonList Object Properties

Property

Description

CellPadding

Gets or sets the distance (in pixels) between the border and contents of the cell.

CellSpacing

Gets or sets the distance (in pixels) between cells.

RepeatColumns

Gets or sets how many columns to display in the CheckBoxList control.

RepeatDirection

Gets or sets a value that indicates whether the control displays vertically or horizontally. Values are Vertical or Horizontal; Vertical is default.

RepeatLayout

Gets or sets the layout of the check boxes. Flow or Table are valid; Table is default. Flow displays items without table structure.

TextAlign

Gets or sets the text alignment for the check boxes within the group. Left or Right are valid; Right is the default.

Visual Basic .NET web_radiobuttonlist_vb.aspx
<%@ page language="vb" runat="server"%>  <%@ Import Namespace="System.Data"%>  <%@ Import Namespace="System.Data.SQLClient"%>  <script runat=server>  Sub Page_Load(sender As Object, e As EventArgs)      if Not IsPostBack then          DataSub      end if  end sub  Sub Select_Shipper(sender As Object, e As EventArgs)      OurText.Text = "Selected Shipper: " + OurRadioList.SelectedItem.Text      OurValue.Text = "Their ShipperID: " + OurRadioList.SelectedItem.Value  End Sub  Sub DataSub()      dim OurCommand as SQLCommand        dim OurConnection as SQLConnection      dim OurDataAdapter as SQLDataAdapter      dim OurDataSet as New DataSet()      OurConnection = New SQLConnection("Server=server;uid=newriders;pwd=password; graphics/ccc.gifdatabase=Northwind")      OurCommand = New SQLCommand("Select ShipperID,CompanyName from Shippers", graphics/ccc.gifOurConnection)      OurDataAdapter = New SQLDataAdapter(OurCommand)      OurDataAdapter.Fill(OurDataSet, "Categories")      dim OurDataTable as New DataView(OurDataSet.Tables("Categories"))      OurRadioList.DataSource = OurDataTable      OurRadioList.DataBind()  End Sub  </script>  <html>  <head>  <title>Simple List Controls - RadioButtonList</title>  </head>  <body bgcolor="#FFFFFF" text="#000000">  <form runat="server">  <h3>Please select your shipper.</h3>  <asp:RadioButtonList            DataTextField="CompanyName"      DataValueField="ShipperID"      BorderColor="#000000"      BorderWidth="1"      BackColor="#EEEEEE"      CellPadding="1"      CellSpacing="1"      AutoPostBack="true"      OnSelectedIndexChanged="Select_Shipper"      runat="server" />  <br><br>  <asp:label  runat="server" /><br>  <asp:label  runat="server" /><br>  </form>  </body>  </html> 
C# web_radiobuttonlist_cs.aspx
<%@ page language="cs" runat="server"%>  <%@ Import Namespace="System.Data"%>  <%@ Import Namespace="System.Data.SqlClient"%>  <script runat=server>  void Page_Load(Object sender, EventArgs e) {     if (!IsPostBack){         DataSub();      }  }  void Select_Shipper(Object sender, EventArgs e){     OurText.Text = "Selected Shipper: " + OurRadioList.SelectedItem.Text;      OurValue.Text = "Their ShipperID: " + OurRadioList.SelectedItem.Value;  }  void DataSub(){     SqlCommand OurCommand;      SqlConnection OurConnection;      SqlDataAdapter OurDataAdapter;      DataSet OurDataSet;      OurDataSet = new DataSet();      OurConnection = new SqlConnection("Server=server;uid=newriders;pwd=password; graphics/ccc.gifdatabase=Northwind");      OurCommand = new SqlCommand("Select ShipperID,CompanyName from Shippers", graphics/ccc.gifOurConnection);      OurDataAdapter = new SqlDataAdapter(OurCommand);      OurDataAdapter.Fill(OurDataSet, "Categories");      DataView OurDataTable = new DataView(OurDataSet.Tables["Categories"]);      OurRadioList.DataSource = OurDataTable;      OurRadioList.DataBind();  }  </script>  <html>  <head>  <title>Simple List Controls - RadioButtonList</title>  </head>  <body bgcolor="#FFFFFF" text="#000000">  <form runat="server">  <h3>Please select your shipper.</h3>  <asp:RadioButtonList            DataTextField="CompanyName"      DataValueField="ShipperID"      BorderColor="#000000"      BorderWidth="1"      BackColor="#EEEEEE"      CellPadding="1"      CellSpacing="1"      AutoPostBack="true"      OnSelectedIndexChanged="Select_Shipper"      runat="server" />  <br><br>  <asp:label  runat="server" /><br>  <asp:label  runat="server" /><br>  </form>  </body>  </html> 

As you can see in Figure 9.5, the RadioButtonList can be controlled and displayed in a similar way to the CheckBoxList. Through the SelectedItem property, you can retrieve both the text and value of the selected option.

Figure 9.5. The RadioButtonList lets you deal with a group of radio buttons as a single object, where you can get and set properties of the all the radio buttons as a set.
graphics/09fig05.gif

This example also uses data binding to populated the RadioButtonList's text and value properties. I also have the RadiobuttonList's AutoPostBack property set to true, so that when a user changes a selection the form posts back.

Repeater Control

The Repeater control is a very flexible server control. It also may appear to be like a small regression back to a spaghetti coding situation, but looks can be deceiving. Look at the Repeater's properties first, and then I'll pull back the veil and show you how the Repeater isn't really spaghetti code at all.

Table 9.6. Repeater Object Properties

Property

Description

DataMember

Gets or sets the table in the data source that will be bound to the control. (Note: In .NET, there are ways that data sources can have multiple tables, and that's what this property is for.)

DataSource

Gets or sets which data source provides the data that the Repeater will contain.

You might be thinking, "What the heck can I do with so few properties?" and to some degree you are correct. There isn't much you can do with just those. Truthfully, according to the .NET Framework, there are more properties than this, but I am going to deal with these specific type of properties in a different way for the rest of this chapter. These properties all fall under a family of properties known as templates.

Using Templates

Truthfully, the Repeater control is the first control where I introduce templates. These templates are what give you the control you need to make bound data appear the way you want.

Templates enable you to format how different components of these objects appear and operate and what they contain. The templates become more abundant and possess greater function as you progress through the next three controls.

I started with the Repeater because it is the simplest of the controls that contain templates. In a nutshell, the Repeater control contains no structure whatsoever. There is no inherent HTML formatting, and you are required to place all form within the Repeater yourself.

This is what may make the Repeater appear that it is similar to spaghetti-type code, but it has all the advantages of being an object. When you populate these templates with code, you are actually setting a property. Get it? You aren't writing spaghetti code; you are populating the related property, which exposes the Repeater to manipulation just like any other object. Table 9.7 looks at the templates available to the Repeater control. All these templates are technically properties of the same name.

Table 9.7. Repeater Object Templates

Template

Description

HeaderTemplate

If specified, rendered one time before anything in any of the other templates.

ItemTemplate

Required; renders once for each item within the bound datasource.

AlternatingItemTemplate

If specified, rendered alternately with ItemTemplate through the items within the bound datasource.

SeparatorTemplate

If specified, renders between each item in the bound datasource.

FooterTemplate

If specified, renders once after all the items of the datasource have been rendered.

Now take a look at a simple example of the Repeater control being used to display and format data.

Visual Basic .NET web_repeater_vb.aspx
<%@ page language="vb" runat="server"%>  <%@ Import Namespace="System.Data"%>  <%@ Import Namespace="System.Data.SQLClient"%>  <script runat=server>  Sub Page_Load(sender As Object, e As EventArgs)      if Not IsPostBack then          DataSub      end if  end sub  Sub DataSub()      dim OurCommand as SQLCommand      dim OurConnection as SQLConnection      dim OurDataAdapter as SQLDataAdapter      dim OurDataSet as New DataSet()      OurConnection = New SQLConnection("Server=server;uid=newriders;pwd=password; graphics/ccc.gifdatabase=Northwind")      OurCommand = New SQLCommand("Select CompanyName,Phone from Shippers",OurConnection)      OurDataAdapter = New SQLDataAdapter(OurCommand)      OurDataAdapter.Fill(OurDataSet, "Categories")      dim OurDataTable as New DataView(OurDataSet.Tables("Categories"))      OurRepeater.DataSource = OurDataTable      OurRepeater.DataBind()  End Sub  </script>  <html>  <head>  <title>Web Repeater</title>  </head>  <body bgcolor="#FFFFFF" text="#000000">  <form runat="server">  <asp:Repeater  runat="server">  <HeaderTemplate>      <u><b>Shippers and PhoneNumbers</b></u><br>  </HeaderTemplate>  <ItemTemplate>      <%# DataBinder.Eval(Container.DataItem, "CompanyName") %>:      <%# DataBinder.Eval(Container.DataItem, "Phone") %><br>  </ItemTemplate>  <FooterTemplate>  This is the end of the phone numbers  </FooterTemplate>  </asp:Repeater>  </form>  </body>  </html> 
C# web_repeater_cs.aspx
<%@ page language="cs" runat="server"%>  <%@ Import Namespace="System.Data"%>  <%@ Import Namespace="System.Data.SqlClient"%>  <script runat=server>  void Page_Load(Object sender, EventArgs e) {     if (!IsPostBack){         DataSub();      }  }  void DataSub(){     SqlCommand OurCommand;      SqlConnection OurConnection;      SqlDataAdapter OurDataAdapter;      DataSet OurDataSet;      OurDataSet = new DataSet();      OurConnection = new SqlConnection("Server=server;uid=newriders;pwd=password; graphics/ccc.gifdatabase=Northwind");      OurCommand = new SqlCommand("Select CompanyName, Phone from Shippers",OurConnection);      OurDataAdapter = new SqlDataAdapter(OurCommand);      OurDataAdapter.Fill(OurDataSet, "Categories");      DataView OurDataTable = new DataView(OurDataSet.Tables["Categories"]);      OurRepeater.DataSource = OurDataTable;      OurRepeater.DataBind();  }  </script>  <html>  <head>    <title>Web Repeater</title>  </head>  <body bgcolor="#FFFFFF" text="#000000">  <form runat="server">  <asp:Repeater  runat="server">  <HeaderTemplate>      <u><b>Shippers and PhoneNumbers</b></u><br>  </HeaderTemplate>  <ItemTemplate>      <%# DataBinder.Eval(Container.DataItem, "CompanyName") %>:      <%# DataBinder.Eval(Container.DataItem, "Phone") %><br>  </ItemTemplate>  <FooterTemplate>  This is the end of the phone numbers  </FooterTemplate>  </asp:Repeater>  </form>  </body>  </html> 

Looking at Figure 9.6, you can see that the Repeater operates just like a Literal control, except it has different players in the different templates. It basically dumps the HTML just as you wrote it to the page.

Figure 9.6. The Repeater allows you to bind data sources to it, and, through the use of templates, display that data.
graphics/09fig06.gif

Building a Complex Repeater

As you can see in the preceding example, the Repeater object simply places the HTML in the templates in the order we want over into the HTML output. This means as far as template creation is concerned, you can go hog wild with what is inside the Repeater. Now look at a much more complicated Repeater with a table with multiple rows per item and a separator, to boot.

Visual Basic .NET web_complexrepeater_vb.aspx
<%@ page language="vb" runat="server"%>  <%@ Import Namespace="System.Data"%>  <%@ Import Namespace="System.Data.SQLClient"%>  <script runat=server>  Sub Page_Load(sender As Object, e As EventArgs)      if Not IsPostBack then          DataSub      end if  end sub  Sub DataSub()      dim OurCommand as SQLCommand      dim OurConnection as SQLConnection      dim OurDataAdapter as SQLDataAdapter      dim OurDataSet as New DataSet()      OurConnection = New SQLConnection("Server=server;uid=newriders;pwd=password; graphics/ccc.gifdatabase=Northwind")      OurCommand = New SQLCommand("Select Top 3 TitleOfCourtesy,FirstName,LastName,Title, graphics/ccc.gifHireDate,Address,City,Region,PostalCode,Country from Employees",OurConnection)      OurDataAdapter = New SQLDataAdapter(OurCommand)      OurDataAdapter.Fill(OurDataSet, "Categories")      dim OurDataTable as New DataView(OurDataSet.Tables("Categories"))      OurRepeater.DataSource = OurDataTable      OurRepeater.DataBind()  End Sub  </script>  <html>  <head>  <title>Web Repeater</title>  </head>  <body bgcolor="#FFFFFF" text="#000000">  <form runat="server">  <asp:Repeater  runat="server">  <HeaderTemplate>      <table width="700" cellpadding="2" cellspacing="1" border="0">      <tr><td colspan="3"><h3>Employees for Northwind</h3></td></tr>  </HeaderTemplate>  <ItemTemplate>        <tr bgcolor="#AAAAAA"><td><b>Name</b></td>      <td><b>Title</b></td>      <td><b>Hire Date</b></td></tr>      <tr bgcolor="#EEEEEE"><td>      <%# DataBinder.Eval(Container.DataItem, "TitleOfCourtesy") %>      <%# DataBinder.Eval(Container.DataItem, "FirstName") %>      <%# DataBinder.Eval(Container.DataItem, "LastName") %>      </td><td>      <%# DataBinder.Eval(Container.DataItem, "Title") %>      </td><td>      <%# DataBinder.Eval(Container.DataItem, "HireDate") %>      </td></tr>      <tr bgcolor="#AAAAAA"><td><b>Address</b></td>      <td><b>City</b></td>      <td><b>Region, Postal Code, Country</b></td></tr>      <tr bgcolor="#EEEEEE"><td>      <%# DataBinder.Eval(Container.DataItem, "Address") %>      </td><td>      <%# DataBinder.Eval(Container.DataItem, "City") %>      </td><td>      <%# DataBinder.Eval(Container.DataItem, "Region") %>      <%# DataBinder.Eval(Container.DataItem, "PostalCode") %>      <%# DataBinder.Eval(Container.DataItem, "Country") %>      </td></tr>  </ItemTemplate>  <SeparatorTemplate>  <tr><td colspan="3"><hr></td></tr>  </SeparatorTemplate>  <FooterTemplate>  </table>  </FooterTemplate>  </asp:Repeater>  </form>  </body>  </html> 
C# web_complexrepeater_cs.aspx
<%@ page language="cs" runat="server"%>  <%@ Import Namespace="System.Data"%>  <%@ Import Namespace="System.Data.SqlClient"%>  <script runat=server>  void Page_Load(Object sender, EventArgs e) {     if (!IsPostBack){         DataSub();      }  }  void DataSub(){     SqlCommand OurCommand;      SqlConnection OurConnection;      SqlDataAdapter OurDataAdapter;      DataSet OurDataSet;      OurDataSet = new DataSet();      OurConnection = new SqlConnection("Server=server;uid=newriders;pwd=password; graphics/ccc.gifdatabase=Northwind");      OurCommand = new SqlCommand("Select Top 3 TitleOfCourtesy,FirstName,LastName,Title, graphics/ccc.gifHireDate,Address,City,Region,PostalCode,Country from Employees",OurConnection);      OurDataAdapter = new SqlDataAdapter(OurCommand);      OurDataAdapter.Fill(OurDataSet, "Categories");      DataView OurDataTable = new DataView(OurDataSet.Tables["Categories"]);      OurRepeater.DataSource = OurDataTable;      OurRepeater.DataBind();  }  </script>  <html>  <head>  <title>Web Repeater</title>  </head>  <body bgcolor="#FFFFFF" text="#000000">  <form runat="server">  <asp:Repeater  runat="server">  <HeaderTemplate>      <table width="700" cellpadding="2" cellspacing="1" border="0">      <tr><td colspan="3"><h3>Employees for Northwind</h3></td></tr>  </HeaderTemplate>  <ItemTemplate>      <tr bgcolor="#AAAAAA"><td><b>Name</b></td>      <td><b>Title</b></td>      <td><b>Hire Date</b></td></tr>      <tr bgcolor="#EEEEEE"><td>      <%# DataBinder.Eval(Container.DataItem, "TitleOfCourtesy") %>      <%# DataBinder.Eval(Container.DataItem, "FirstName") %>      <%# DataBinder.Eval(Container.DataItem, "LastName") %>      </td><td>      <%# DataBinder.Eval(Container.DataItem, "Title") %>      </td><td>      <%# DataBinder.Eval(Container.DataItem, "HireDate") %>      </td></tr>      <tr bgcolor="#AAAAAA"><td><b>Address</b></td>      <td><b>City</b></td>      <td><b>Region, Postal Code, Country</b></td></tr>      <tr bgcolor="#EEEEEE"><td>      <%# DataBinder.Eval(Container.DataItem, "Address") %>      </td><td>      <%# DataBinder.Eval(Container.DataItem, "City") %>      </td><td>      <%# DataBinder.Eval(Container.DataItem, "Region") %>      <%# DataBinder.Eval(Container.DataItem, "PostalCode") %>      <%# DataBinder.Eval(Container.DataItem, "Country") %>      </td></tr>    </ItemTemplate>  <SeparatorTemplate>  <tr><td colspan="3"><hr></td></tr>  </SeparatorTemplate>  <FooterTemplate>  </table>  </FooterTemplate>  </asp:Repeater>  </form>  </body>  </html> 

As you can see in the results displayed in Figure 9.7, the only real limitation as to what you can have a Repeater do is you. You can place any valid HTML in the Repeater, and it will render it to the browser.

Figure 9.7. You can build very complex HTML databound objects with the Repeater control.
graphics/09fig07.gif

Tip

One thing to watch out for, as with the literal control, is that the Repeater renders to the browser what it contains. If you are delivering anything from a data source that might be interpreted as HTML, such as arrows (< or >), this will cause the browser to flake out and not give you the desired results. Any time you might be delivering data to a Repeater that might contain confusing characters such as these, I recommend that you HTMLEncode it this way: Server.HTMLEncode(DataBinder.Eval(Container.DataItem, "Address"))


Don't be afraid to experiment and see what interesting things you can come up with when using the Repeater. Although it does require you to code the templates, it also provides an abundance of freedom in displaying bound data.


   
Top


ASP. NET for Web Designers
ASP.NET for Web Designers
ISBN: 073571262X
EAN: 2147483647
Year: 2005
Pages: 94
Authors: Peter Ladka

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