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





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.


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.


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.


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.

<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).


<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>
<p><asp:button id=Button1
Text="Push to generate the table"></asp:button></FORM></P>


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" %>
<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",
        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;

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

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

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

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

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

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

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

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

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

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

<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"



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



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


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


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


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


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.


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" %>

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

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

         dt.Columns.Add(new DataColumn("StringValue",

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

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

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

      void Button1_Click(Object sender, EventArgs e)

         DataList1.RepeatDirection = RepeatDirection.Horizontal;

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


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



   <form runat=server>

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

      <asp:DataList id="DataList1" runat="server"

         <HeaderStyle BackColor="#aaaadd">

         <ItemStyle BackColor="Gainsboro">


            Cell Item #



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



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



      <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 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:LinkButton id=Button1
           Text="Refresh DataList"



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.

<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;

        Repeater2.DataSource = values;

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;



    <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>


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


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



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







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


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

                Broome Community College data:

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



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



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

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information

To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.


Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.


If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information

Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.


This site is not directed to children under the age of 13.


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information

If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information

Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents

California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure

Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact

Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice

We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020