Home > Articles > Programming > C#

📄 Contents

  1. Send It Out
  2. Send It Out—In a List
  3. Summary
  • Print
  • + Share This
This chapter is from the book

This chapter is from the book

Send It Out—In a List

In the previous section, you learned how to send information to various controls. The information sent was usually a string or a string of information formatted in a particular manner. You learned that simple formatting techniques could provide tabular lists of data in various controls.

In this section, you will learn how to incorporate various controls that are capable of displaying lists on Web pages. There are essentially four types of controls designed for creating lists:

  • Table control
  • DataGrid control
  • DataList control
  • Repeater control

Table 8.5 briefly lists each control type followed by a column of suggested uses and a column of advantages and capabilities.

Table 8.5 ASP.NET Controls for Displaying Lists

Control

Use

Advantages/Capabilities

DataGrid

Provides a full-featured list output with editing capabilities.

The appearance of the table can be customized. A grid appearance is the default. Autoformatting is possible with output using a variety of options, including bound columns, columns of buttons or hyperlinks, and custom columns created using templates. Provides support for single and multiple selections.

 

 

No separator template is required. The contents can be edited, sorted, and deleted.

DataList

Provides easy customizable list output with editing

The appearance of the table can be customized.

 

 

This includes autoformatting. List items support styles that can provide a unique look. Separators between individual elements can use templates.

 

 

Provides support for single and multiple selections. The layout supports columns or rows, with multiple columns an option.

 

 

All data in this control is displayed in a single list.

Repeater

Provides simple, read-only list output.

The appearance of a Repeater control is governed by the use of templates, therefore there is no inherent look for this control. No support is provided for selection or editing since this is a read-only control. Separators between individual elements can use templates.

 

 

All data in this control is displayed in a single list.

Table

Provides list output in a simple programmable table format.

This control is unique in that it is not data-bound. It can be used to display various combinations of HTML text and HTML controls. The Table control does not use templates. Rows are created with TableRow controls and cells with TableCell controls.


In the following sections, we'll examine Table, DataGrid, DataList, and Repeater controls in more detail and provide you with a simple application for each type. The applications we have provided are modifications of examples provided with Microsoft SDK.

Using Table Controls

The Table Web server control is used to create server-programmable tables on a Web Forms page. By using the TableRow and TableCell server controls, the content of the Table control can be displayed.

Table controls are usually used as a way to present tabular information and as a way to format information on a Web page. The Table control is usually used when it is desirable to add rows and columns at runtime.

The Table control accomplishes many of the same feats as the other list controls (DataGrid, DataList, and Repeater). The basic difference is that the three list controls are data bound and work against a data source. Table controls, on the other hand, are not necessarily data bound and can display any combinations of text and controls.

The Table control does not use templates, as do the other list controls, but relies on the TableCell and TableRow controls. For example, Table controls have a Rows property that is a collection of TableRow objects. The TableRow control supports a collection called Cells made up of TableCell objects. The TableCell control is then used to display a given cell.

The application for this section is named TblCtrl. The following code listing is the complete code required for this project. First, create a new C# project for the Web named TblCtrl. From the Design View pane, switch to the HTML View pane and enter the following code.

<html><head>
<script language=C# runat="server">

void Page_Load(Object sender, EventArgs e) {

    int numcells = int.Parse(DropDown1.SelectedItem.Value);
    int numrows = int.Parse(DropDown2.SelectedItem.Value);
    string tempstr = "";

    // Generate rows and columns
    for (int j = 0; j < numrows; j++) {
        TableRow tr = new TableRow();
        for (int i = 0; i < numcells; i++) {
            if (i == 0) tempstr = "A";
            else if (i == 1) tempstr = "B";
            else if (i == 2) tempstr = "C";
            else if (i == 3) tempstr = "D";
            else if (i == 4) tempstr = "E";
            else if (i == 5) tempstr = "F";
            else if (i == 6) tempstr = "G";
            else if (i == 7) tempstr = "H";

            TableCell tc = new TableCell();
            tc.Controls.Add(new LiteralControl
                           (tempstr + (j + 1).
                           ToString()));
            tr.Cells.Add(tc);
        }
        Table1.Rows.Add(tr);
    }
}

</script>

</HEAD>
<body>
<h3><font face=Arial>Using Table Web
Controls </FONT></H3>
<form id=Form1 runat="server">
<asp:table id=Table1 runat="server" Gridlines="Both"
           BorderWidth="2" BorderColor="black"
           CellSpacing="0" CellPadding="5"
           Font-Size="10pt" Font-Name="Arial"></asp:Table>
<p><br>Number of Columns:
<asp:dropdownlist id=DropDown1 runat="server">
       <asp:ListItem Value="1">A</asp:ListItem>
       <asp:ListItem Value="2">B</asp:ListItem>
       <asp:ListItem Value="3">C</asp:ListItem>
       <asp:ListItem Value="4">D</asp:ListItem>
       <asp:ListItem Value="5">E</asp:ListItem>
       <asp:ListItem Value="6">F</asp:ListItem>
       <asp:ListItem Value="7">G</asp:ListItem>
       <asp:ListItem Value="8">H</asp:ListItem>
</asp:DropDownList><br><br>Number of Rows:
<asp:dropdownlist id=DropDown2 runat="server">
       <asp:ListItem Value="1">1</asp:ListItem>
       <asp:ListItem Value="2">2</asp:ListItem>
       <asp:ListItem Value="3">3</asp:ListItem>
       <asp:ListItem Value="4">4</asp:ListItem>
       <asp:ListItem Value="5">5</asp:ListItem>
       <asp:ListItem Value="6">6</asp:ListItem>
       <asp:ListItem Value="7">7</asp:ListItem>
       <asp:ListItem Value="8">8</asp:ListItem>
</asp:DropDownList>
<p><asp:button id=Button1
runat="server"
Text="Push to generate the table"></asp:button></FORM></P>

</body></HTML>

Once you have entered the code, build and test the application in the normal manner.

Figure 8.13 shows the control placement and Properties pane while in Design mode.

Figure 8.13Figure 8.13 Control placement for the TblCtrl project.


When the project is executed, you'll see how the project will generate a table where the user can specify the number of columns and rows.

Figure 8.14 shows the TblCtrl project during execution with four columns and three rows.

Figure 8.14Figure 8.14 The TblCtrl project during execution.


The cell data for the TblCtrl project gives cell data as it might be specified in a spreadsheet.

Using DataGrid Controls

The DataGrid Web server control is used to display tabular data on a Web form. The control supports selecting, editing, sorting, and paging for the bound data. This control is bound to a data source using the DataSource property in order for it to be rendered on the Web page.

The data source can be a class that supports the ICollection interface. The DataGrid control's grid then displays one row for every row in the data source. The control creates a bound column for each field in the data source, but which field generates a column in the grid can be specified.

The DataBind method is used to gather data for the grid. Grid columns are generated automatically based on fields in the data source but can be manipulated via bound columns, hyperlinks, button controls, Edit command columns, Template columns, and so on. For more details, use the Visual Studio.NET Help facility on this topic.

Sorting data is not directly supported, but allows you to add sort options to the grid. One technique is to use link buttons as column heads. Then, when the user clicks on a link button, a sort notification is raised.

In the application in this section, named DGCtrl, a DataGrid is used that will produce a three column and nine row grid.

To create this project, start a new C# Web project named DGCtrl and enter the following code while in the HTML Design pane.

<%@ Import Namespace="System.Data" %>
<html><head>
<script language=C# id=Script1 runat="server">

    ICollection CreateDataSource() {
        DataTable dt = new DataTable();
        DataRow dr;

        DateTime nowdt;
        nowdt = DateTime.Now;

        // Create a DataGrid with three columns
        dt.Columns.Add(new DataColumn("Item #", typeof(Int32)));
        dt.Columns.Add(new DataColumn("Date/Time Component",
                                      typeof(string)));
        dt.Columns.Add(new DataColumn("Value", typeof(Int32)));

        // Add Row information for Year
        dr = dt.NewRow();
        dr[0] = 1;
        dr[1] = "Year";
        dr[2] = nowdt.Year;
        dt.Rows.Add(dr);

        // Add Row information for Month
        dr = dt.NewRow();
        dr[0] = 2;
        dr[1] = "Month";
        dr[2] = nowdt.Month;
        dt.Rows.Add(dr);

        // Add Row information for Day
        dr = dt.NewRow();
        dr[0] = 3;
        dr[1] = "Day";
        dr[2] = nowdt.Day;
        dt.Rows.Add(dr);

        // Add Row information for Day of Year
        dr = dt.NewRow();
        dr[0] = 4;
        dr[1] = "Day of Year";
        dr[2] = nowdt.DayOfYear;
        dt.Rows.Add(dr);

        // Add Row information for DayOfWeek
        dr = dt.NewRow();
        dr[0] = 5;
        dr[1] = "Day of Week";
        dr[2] = nowdt.DayOfWeek;
        dt.Rows.Add(dr);

        // Add Row information for Hour
        dr = dt.NewRow();
        dr[0] = 6;
        dr[1] = "Hour";
        dr[2] = nowdt.Hour;
        dt.Rows.Add(dr);

        // Add Row information for Minutes
        dr = dt.NewRow();
        dr[0] = 7;
        dr[1] = "Minutes";
        dr[2] = nowdt.Minute;
        dt.Rows.Add(dr);

        // Add Row information for Seconds
        dr = dt.NewRow();
        dr[0] = 8;
        dr[1] = "Seconds";
        dr[2] = nowdt.Second;
        dt.Rows.Add(dr);

        // Add Row information for Milliseconds
        dr = dt.NewRow();
        dr[0] = 9;
        dr[1] = "Milliseconds";
        dr[2] = nowdt.Millisecond;
        dt.Rows.Add(dr);

        DataView dv = new DataView(dt);
        return dv;
    }

    void Page_Load(Object sender, EventArgs e) {
        MyDataGrid.DataSource = CreateDataSource();
        MyDataGrid.DataBind();
    }

</script>
</head>
<body>
<h3><font face=Arial>Using the
DataGrid Web Control</FONT></H3>
<h3><font face=Arial color=green>Current Date &amp; Time Information</FONT></H3>

<form runat=server ID=Form1>

  <ASP:DataGrid id="MyDataGrid" runat="server"
                BorderColor="Blue"
                BorderWidth="1"
                GridLines="Both"
                CellPadding="3"
                CellSpacing="0"
                Font-Name="Arial"
                Font-Size="Medium"
                HeaderStyle-BackColor="#aaaadd"
                backcolor="#C0FFC0"
                font-names="Arial"/>

</form>

</body></html>

It is easy to see how each column and row is added to the DataGrid control by examining this code. The cells of the control are filled with both string and integer data.

Figure 8.15 shows the placement of the controls when you switch back to the Design pane.

Figure 8.15Figure 8.15 Placement of controls for the DGCtrl project.


Figure 8.16 shows the execution of the application.

Figure 8.16Figure 8.16 Output from the DGCtrl project.


The output for the DGCtrl project is a well-formatted grid showing an item number, text string, and data value for date and time information returned by the system.

Using DataList Controls

The DataList Web control is used to display database information. The control provides the advantage of being able to format this data by using templates and styles. The DataList control is useful for displaying rows of database information as items in the list. The layout of the items is governed by using HTML text and controls.

The DataList control, like the DataGrid control, is bound to a data source. This control also uses any data source class that supports the ICollection interface. The DataList control uses templates to specify the layout. Table 8.6 provides a list and description of DataList templates.

Table 8.6  DataList Control Templates

Template Option

Description

AlternatingItemTemplate

Similar to the ItemTemplate element. Renders every other row in the DataList control. Typically used to shade alternate cells in a different color.

EditItemTemplate

Specifies the layout of an item when it is in edit mode. Provides editing controls.

HeaderTemplate/FooterTemplate

Specifies the text and controls that will be rendered at the start and end of the list.

ItemTemplate

Specifies the HTML elements and controls that are rendered for each row in the data source.

SelectedItemTemplate

Specifies the HTML elements that are rendered when an item is selected from the DataList control. A switch in background or foreground color is typical.

SeparatorTemplate

Specifies the elements that are rendered between each item.


The application for this section is named DLCtrl. To create this project, open a new C# Web project named DLCtrl. From the HTML tab of the Designer pane, enter the code shown in the following listing.

<%@ Import Namespace="System.Data" %>

<HTML>
   <script language = "C#" runat="server">

      ICollection CreateDataSource()
      {
         DataTable dt = new DataTable();
         DataRow dr;

         dt.Columns.Add(new DataColumn("StringValue",
                                        typeof(string)));

         for (int i = 0; i < 21; i++)
         {
            dr = dt.NewRow();
            dr[0] = "Cell " + (i + 1).ToString();
            dt.Rows.Add(dr);
         }

         DataView dv = new DataView(dt);
         return dv;
      }

      void Page_Load(Object sender, EventArgs e)
      {
         if (!IsPostBack)
         {
            DataList1.DataSource = CreateDataSource();
            DataList1.DataBind();
         }
      }

      void Button1_Click(Object sender, EventArgs e)
      {

         DataList1.RepeatDirection = RepeatDirection.Horizontal;

         if (DropDown1.SelectedIndex == 0)
            DataList1.RepeatLayout = RepeatLayout.Table;
         else
            DataList1.RepeatLayout = RepeatLayout.Flow;

         DataList1.RepeatColumns=DropDown2.SelectedIndex+1;

         DataList1.BorderWidth = Unit.Pixel(1);
         DataList1.GridLines = GridLines.Both;
      }

   </script>

<body>

   <form runat=server>

      <h3><font face="Arial">Using A DataList Control
      </font></h3>

      <asp:DataList id="DataList1" runat="server"
           BorderColor="black"
          CellPadding="3"
           Font-Name="Arial"
           Font-Size="8pt">

         <HeaderStyle BackColor="#aaaadd">
         </HeaderStyle>

         <ItemStyle BackColor="Gainsboro">
         </ItemStyle>

         <HeaderTemplate>

            Cell Item #

         </HeaderTemplate>

         <ItemTemplate>

            <%# DataBinder.Eval(Container.DataItem,
                                "StringValue") %>

         </ItemTemplate>

      </asp:DataList>

      <p>
      <hr noshade align="left" width="300"

      <br>

      RepeatLayout:

      <asp:DropDownList id=DropDown1 runat="server">
<asp:ListItem Value="Table Format">Table Format</asp:ListItem>
<asp:ListItem Value="Flow Format">Flow Format</asp:ListItem>

      </asp:DropDownList><br>

      RepeatColumns:

      <asp:DropDownList id=DropDown2 runat="server">
<asp:ListItem Value="1">1</asp:ListItem>
<asp:ListItem Value="2">2</asp:ListItem>
<asp:ListItem Value="3">3</asp:ListItem>
<asp:ListItem Value="4">4</asp:ListItem>
<asp:ListItem Value="5">5</asp:ListItem>
<asp:ListItem Value="6">6</asp:ListItem>
<asp:ListItem Value="7">7</asp:ListItem>
<asp:ListItem Value="8">8</asp:ListItem>
<asp:ListItem Value="9">9</asp:ListItem>
<asp:ListItem Value="10">10</asp:ListItem>


      </asp:DropDownList><br>


      <asp:LinkButton id=Button1
           Text="Refresh DataList"
           OnClick="Button1_Click"
           runat="server"/>

   </form>

</body>
</HTML>

This application creates a table or flow format for the data. The cell placement is horizontal. This means the cells will be placed sequentially in the horizontal direction until filled. The actual placement of cell information is dependent upon the number of columns used in the DataList control.

Figure 8.17 shows the placement of the project's controls.

Figure 8.17Figure 8.17 Control placement in the DLCtrl project.


When the application is executed, your screen should be similar to Figure 8.18.

Figure 8.18Figure 8.18 Execution of the DLCtrl project.


Experiment with this application and note the results for the previous conditions when a flow layout is selected.

Using Repeater Controls

The Repeater Web server control is used to create custom lists from any available data. Unlike the DataGrid and DataList controls, the Repeater control does not have an inherent look. The layout of the Repeater control is controlled by templates. When the Web page runs, the Repeater control loops through the data source records and renders an item for each record.

Since the Repeater control's layout is controlled by templates, it can be used to generate a bulleted list, numbered list, comma delimited list, a table or grid, and more.

The templates that control the layout can contain combinations of HTML text and controls. See Table 8.6, shown earlier, for a list and description of template types supported by the Repeater control.

The Repeater control, like the DataGrid and DataList controls, must be bound to a data source using the DataSource property. Also, like the DataGrid and DataList controls, this control can use any data source class that supports the ICollection interface. In addition, the Repeater control supports the IEnumerable interface.

The Repeater control supports two events: ItemCreated and ItemCommand. The ItemCreated event allows customization of the item creation process. The ItemCommand event fires when an individual item is selected with a button click.

The application for this section is named RepCtrl. To create this application, start a new C# Web project and name it RepCtrl. From the HTML tab of the Design pane, enter the following project code.

<html>
<head>
<script language="C#" runat="server" ID=Script1>

void Page_Load(Object Sender, EventArgs e) {

    if (!IsPostBack) {

        ArrayList values = new ArrayList();

        values.Add(new PositionData("William Beston",
                       "Dean of Technology (retired)"));
        values.Add(new PositionData("Shannon Covert",
                       "CST - Full Time Adjunct"));
        values.Add(new PositionData("Donald Dellow",
                       "President - Broome Community College"));
        values.Add(new PositionData("Alan Dixon",
                       "EET - Professor (retired)"));
        values.Add(new PositionData("Mort Goldberg",
                       "Math - Professor (retired)"));
        values.Add(new PositionData("Rachel Hinton",
                       "CST - Assistant Professor"));
        values.Add(new PositionData("Gary Kohut",
                       "CST - Technician"));
        values.Add(new PositionData("Ken Mansfield",
                       "CST - Associate Professor"));
        values.Add(new PositionData("Beth Mollen",
                       "CST - Associate Professor"));
        values.Add(new PositionData("William Murray",
                       "EET - Department Chair"));
        values.Add(new PositionData("Chris Pappas",
                       "CST - Department Chair"));
        values.Add(new PositionData("Julie Peacock",
                       "Dean of Technology"));
        values.Add(new PositionData("Lydia Smith",
                       "CST / EET Department Secretary"));

        Repeater1.DataSource = values;
        Repeater1.DataBind();

        Repeater2.DataSource = values;
        Repeater2.DataBind();
    }
}

public class PositionData {

    private string name;
    private string position;

    public PositionData(string name, string position) {
        this.name = name;
        this.position = position;
    }

    public string Name {
        get {
            return name;
        }
    }

    public string Position {
        get {
            return position;
        }
    }
}

</script>

</head>
<body>

    <h3><font face="Arial" color=blue
              size=12>Using Repeater Web Controls</font></h3>

    <form runat=server ID=Form1>

        <b>From Repeater Control #1:</b>

        <p>

        <asp:Repeater id=Repeater1 runat="server">

            <HeaderTemplate>

                <table border=1>
                  <tr>
                    <td><b>Employee Name</b></td>
                    <td><b>Employee Position</b></td>
                  </tr>

            </HeaderTemplate>

            <ItemTemplate>

                <tr>
                  <td> <%# DataBinder.Eval(Container.DataItem,
                           "Name") %> </td>
                  <td> <%# DataBinder.Eval(Container.DataItem,
                           "Position") %> </td>
                </tr>

            </ItemTemplate>

            <FooterTemplate>

                </table>

            </FooterTemplate>

        </asp:Repeater>

        <p>

        <b>From Repeater Control #2:</b>

        <p>

        <asp:Repeater id=Repeater2 runat="server">

            <HeaderTemplate>
                Broome Community College data:
            </HeaderTemplate>

            <ItemTemplate>
                <%# DataBinder.Eval(Container.DataItem,
                                    "Name") %>
               [<%# DataBinder.Eval(Container.DataItem,
                                    "Position") %>]
            </ItemTemplate>

            <SeparatorTemplate>,
            </SeparatorTemplate>

        </asp:Repeater>

<asp:Repeater id=Repeater3 runat="server"></asp:Repeater>

    </form></P>

</body>
</html>

As you study this code, you will notice the use of several templates for the layout of the Repeater control's data.

Also note that two Repeater controls are used. The first renders the data in a table format while the second control renders the data in a flow format using comma delimiters.

Figure 8.19 shows the layout of the controls in Design mode once the previous code is entered in the HTML pane.

Figure 8.19Figure 8.19 Control placement for the RepCtrl project.


Figure 8.20 shows the output from the RepCtrl project.

Figure 8.20Figure 8.20 Data is rendered differently using two Repeater controls.


You'll have to agree that the Repeater control provides the most flexibility in rendering list data.

  • + Share This
  • 🔖 Save To Your Account