Figure 1

Figure 1 ASP .NET List Controls
Tag
Description
<asp:DropDownList>
Combobox whose display text and value can be associated with fields of a data source
<asp:ListBox>
Listbox whose display text and value can be associated with fields of a data source
<asp:CheckBoxList>
List of checkboxes whose display text and value can be associated with fields of a data source
<asp:RadioButtonList>
List of radio buttons whose display text and value can be associated with fields of a data source
<asp:DataGrid>
Displays tabular data and optionally supports selecting, editing, sorting, and paging the data
<asp:DataList>
Displays database information in a format that you can control very precisely using templates and styles
<asp:Repeater>
Basic container control that allows you to create templatized lists of any data available to the page
Figure 2 Data-bound Controls
<%@ Import Namespace="System.Data.SQL" %>
<%@ Import Namespace="System.Data" %>
<%@ Page Language="C#" %>

<html><head>
<script runat=server>
public void Page_Load(Object Sender, EventArgs e)
{
    // Initialize only the first time...
    if (!Page.IsPostBack)
    {
        // Populates the combobox from an array
        ArrayList a = new ArrayList();
        a.Add("Yellow");
        a.Add("Green");
        a.Add("Blue");
        a.Add("Red");
        DDList.DataSource = a;
        
        // Get some data from Northwind
        String strConn, strCmd;
        strConn = "DATABASE=Northwind;SERVER=localhost;UID=sa;PWD=;";
        strCmd = "SELECT employeeid, firstName + ' ' + lastName AS 
                 'EmployeeName' From Employees";
        SQLDataSetCommand oCMD = new SQLDataSetCommand(strCmd, strConn);
        DataSet oDS = new DataSet();
        oCMD.FillDataSet(oDS, "EmployeesList");
        
        EmpList.DataSource = oDS.Tables["EmployeesList"].DefaultView;
        EmpList.DataTextField = "EmployeeName";
        EmpList.DataValueField = "employeeid";        
    }
    
    // (re)Bind all controls in the page
    Page.DataBind();
}
</script>
</head>
<body>
<b>Synchronized Controls</b>
<form runat=server>
    
    <asp:textbox autopostback=True id=MainTextBox runat=Server >
    </asp:textbox>
    <asp:textbox Text='<%# "Current Value: " + MainTextBox.Text %>' 
         runat=server id=Textbox1></asp:textbox>

<hr>

    <asp:dropdownlist autopostback=True runat=Server id=DDList />
    <asp:Label id=Statusbar runat="server"  text='<%# "Selected: " + 
         DDList.SelectedItem.Text %>' />

<hr>

    <asp:dropdownlist autopostback=True runat=Server id=EmpList />
    <asp:Label id=EmpID runat="server"  text='<%# "Employee ID: " + 
         EmpList.SelectedItem.Value %>' />

</form>
</body></html>
Figure 6 Records with Colored Fields
<%@ Import Namespace="System.Data.SQL" %>
<%@ Import Namespace="System.Data" %>
<%@ Page Language="C#" %>
<html><head>

<script runat="server">
public void Page_Load(Object Sender, EventArgs e)
{

}

public void SearchData(Object Sender, EventArgs e)
{
    // Execute the command
    String strConn, strCmd;

    strConn = "DATABASE=Northwind;SERVER=localhost;UID=sa;PWD=;";
    strCmd = queryText.Text;
        
    SQLDataSetCommand oCMD = new SQLDataSetCommand(strCmd, strConn);

    // Add a named table to the dataset 
    DataSet oDS = new DataSet();
    oCMD.FillDataSet(oDS, "EmployeesList");

    DataGrid1.DataSource = oDS.Tables["EmployeesList"].DefaultView;
    DataGrid1.DataBind();
}

</script>
</head>

<body>
<%
    Session["Logo"] = "../../images/expoware.gif";
    Server.Execute("../../layout.aspx");
%>

<!— ASP .NET Pages can contain just one server-side form —>

<form runat=server>

    <asp:Label id=Label1 runat="server" ForeColor="Black" 
               Font-Bold="True">Query</asp:Label>
    <asp:TextBox id=queryText runat="server">
    select employeeid,firstname,lastname from employees
    </asp:TextBox>

    <asp:Button id=Search runat="server" OnClick="SearchData" 
                Text="Search...">
    </asp:Button>
    <hr>

<!— Show the information —> 

    <asp:DataGrid id=DataGrid1 runat="server" ForeColor="Black" 
                  height="287px" width="411px" 
        font-names="Verdana" font-size="Smaller">

        <property name="AlternatingItemStyle">
            <asp:TableItemStyle BackColor="Gainsboro" />
        </property>

        <property name="ItemStyle">
            <asp:TableItemStyle BackColor="White" />
        </property>

        <property name="HeaderStyle">
            <asp:TableItemStyle Font-Bold="True" ForeColor="White" 
                                BackColor="Navy" />
        </property>
    </asp:DataGrid>

</form>
</body>
</html>
Figure 7 DataGrid Control Elements
Item Type
Description
Header
Represents the table's caption. Cannot be bound to a data source.
Item
Represents the normal data-bound record displayed through the grid.
Separator
Represents a null item used to separate rows. Not data-bound.
AlternatingItem
Represents the alternative record in case you want to use different styles for alternating rows. Data-bound object is placed on even indexes.
EditItem
Represents the DataGrid item to be used when in edit mode. It is data-bound.
Pager
Represents the pager element you can place around the grid to scroll back and forth between pages. It is not data-bound.
SelectedItem
Represents the DataGrid item to be used when in selection mode. It is data-bound.
Footer
Represents the table's footer. Cannot be bound to a data source.
Figure 8 DataGrid Control Properties
Property
Description
AllowCustomPaging, AllowPaging
Both properties get or set a value that indicates whether custom paging or paging is allowed
AllowSorting
Boolean value that enables or disables sorting capability
AlternatingItemStyle, ItemStyle
Returns TableItemStyle objects to set attributes on the item and the alternating item elements
AutoGenerateColumns
False if you want to generate the columns yourself
BackColor, ForeColor
Background and foreground color for the grid
BackImageURL
URL of the image to be used to fill the grid background
BorderColor, BorderWidth, BorderStyle
Properties to customize the grid border
CellPadding, CellSpacing
Get and set respectively the space between content and border and between adjacent cells
CurrentPageIndex
The index of the page currently displayed
DataKeyField
Indicates the primary key field in the data source referenced by DataSource
DataSource
Identifies the data source used to populate the grid
EditItemIndex
The index of the item to be edited
EditItemStyle
Returns a TableItemStyle object to set attributes on the item to be edited
Font
Returns font information
HeaderStyle, FooterStyle
Returns TableItemStyle objects to set attributes on the header and footer items
GridLines
Gets and sets the grid lines style
MaintainState
Set to true if the view state should be maintained
PageSize, PageCount
The number of items to display on a single page and the total number of pages, respectively
PagerStyle
Returns a TableItemStyle object to set attributes on the pager element
SelectedIndex
The index of the item currently selected
SelectedItem
Returns the object representing the currently selected item in the grid
SelectedItemStyle
Returns a TableItemStyle object to set attributes on the currently selected item
ShowFooter, ShowHeader
Both properties get or set a value that indicates whether a header and footer must be shown
VirtualItemCount
The total number of items in the grid used to calculate the index of the first item in case of custom paging
Width, Height
Width and height of the grid
Collection
Description
Items
DataGridItem objects representing the individual items in the grid
DataBindings
All data bindings on the control
Columns
Column objects, each of which represents a grid column
DataKeys
Primary key field names created by evaluating the DataKeyField value
Attributes
Arbitrary attributes for rendering only
Figure 9 Tag Attributes
<asp:DataGrid id="grid" runat="server" 
    CellPadding="4"
    CellSpacing="2"
    GridLines="none"
    HeaderStyle-font-name="verdana"    
    HeaderStyle-font-size="12"    
    HeaderStyle-font-bold="true"        
    HeaderStyle-backcolor="brown"
    HeaderStyle-forecolor="white"
    ItemStyle-backcolor="beige"
    ItemStyle-font-name="verdana"    
    ItemStyle-font-size="11"    
    AlternatingItemStyle-backcolor="palegreen"
/>
Figure 10 Visual Studio .NET Syntax
<asp:DataGrid id="grid" runat="server" 
    CellPadding="4"
    CellSpacing="2"
    GridLines="none">

<property name="AlternatingItemStyle">
<asp:TableItemStyle 
     BackColor="palegreen" />
</property>

<property name="ItemStyle">
<asp:TableItemStyle 
     BackColor="beige" />
</property>

<property name="HeaderStyle">
<asp:TableItemStyle 
     Font-Bold="True" 
     Font-Name="verdana"
     ForeColor="white" 
     BackColor="brown" />
</property>
</asp:DataGrid>
Figure 12 Using the DataGrid Component
<%@ Import Namespace="System.Data.SQL" %>
<%@ Import Namespace="System.Data" %>
<%@ Page Language="C#" %>

<html><head>

<script runat="server">
public void Page_Load(Object Sender, EventArgs e)
{
    SetGridProperties();    
}

/*
    This function creates the data source whenever it is 
    necessary. If you're going to use paging you always 
    need to reload the data source before re-binding. 
    You cannot cache the dataset in this case.
*/
private ICollection CreateDataSource(String strCmd)
{
    // Set up the SQL2K connection
    String strConn;
    strConn = "DATABASE=Northwind;SERVER=localhost;UID=sa;PWD=;";

    // Execute the command and add a named table to the dataset
    SQLDataSetCommand oCMD = new SQLDataSetCommand(strCmd, strConn);

    // Add a named table to the dataset 
    DataSet oDS = new DataSet();
    oCMD.FillDataSet(oDS, "EmployeesList");
    
    // Return a given data table
    return oDS.Tables["EmployeesList"].DefaultView;
}


/*
    The paging needs this delegate handler to refresh the
    data source. It's critical that you recalculate the data
    source here. Internally, the DataGrid will load only the 
    needed elements.
*/
public void Grid_Change(Object Sender, DataGridPageChangedEventArgs e)
{
    DataGrid1.DataSource = CreateDataSource(queryText.Text);
    DataGrid1.DataBind();
}


/*
    This function gets called whenever the user changes 
    the SQL command to fill the DataGrid with new records.
*/
public void SearchData(Object Sender, EventArgs e)
{
    SetGridProperties();
    DataGrid1.DataSource = CreateDataSource(queryText.Text);
    DataGrid1.DataBind();
}


/*
    This function makes sure the DataGrid reflects some properties 
    set dynamically.
*/
private void SetGridProperties()
{
    if (IndicatePageNumbers.Checked)
        DataGrid1.PagerStyle.Mode = PagerMode.NumericPages;
    else
        DataGrid1.PagerStyle.Mode = PagerMode.NextPrev;

    DataGrid1.PagerStyle.PageButtonCount =       
        IndicateNumberOfPages.Text.ToInt32();
    DataGrid1.PageSize = IndicatePageSize.Text.ToInt32();    
}

</script>
</head>

<body>
<%
    Session["Logo"] = "../../images/expoware.gif";
    Server.Execute("../../layout.aspx");
%>

<!-- ASP .NET Pages can contain just one server-side form -->
<form id=Form1 runat="server">
<asp:label runat="server" Font-Bold="True" ForeColor="Black">Query
</asp:label>
<asp:textbox id=queryText runat="server">
SELECT employeeid, firstname, lastname FROM employees</asp:textbox>
<asp:button id=Search onclick="SearchData" runat="server" Text="Go">
</asp:button>

<table border=0><tr>
<td>
<asp:Label runat="server" Font-Bold="True">Page Size</asp:Label>
<asp:TextBox id=IndicatePageSize runat="server" AutoPostBack="true">4
</asp:TextBox> 
</td>

<td> 
<asp:CheckBox id=IndicatePageNumbers runat="server" Text="Indicate page 
     numbers" Checked="True" AutoPostBack="true">
</asp:CheckBox>
</td>

<td> 
<asp:Label runat="server" Font-Bold="True">Page buttons to show</asp:Label>
<asp:TextBox id=IndicateNumberOfPages runat="server" AutoPostBack="true">10
</asp:TextBox>
</td>
</tr></table>

<hr>


<!-- Show the information -->&nbsp; 
<asp:datagrid id=DataGrid1 runat="server" 
    ForeColor="Black" 
    font-size="Smaller" 
    font-names="Verdana" 
    width="411px" 
    AllowPaging="True" 
    OnPageIndexChanged="Grid_Change">

    <property name="PagerStyle">
        <asp:DataGridPagerStyle PageButtonCount="3" Mode="NumericPages" />
    </property>

    <property name="AlternatingItemStyle">
        <asp:TableItemStyle BackColor="Gainsboro" />
    </property>

    <property name="ItemStyle">
        <asp:TableItemStyle BackColor="White" />
    </property>

    <property name="HeaderStyle">
        <asp:TableItemStyle Font-Bold="True" 
            ForeColor="White" 
            BackColor="Navy" />
    </property>
</asp:datagrid>

</form>
</body></html>
Figure 13 Associating a Behavior with Buttons
public void Grid_NewItem(Object Sender, DataGridItemEventArgs e)
{
    // Get the newly created item
    ListItemType itemType = e.Item.ItemType;
    
    // Is it the pager?
    if (itemType == ListItemType.Pager) {
        // There's just one control in the list...
        TableCell pager = (TableCell)e.Item.Controls[0];
        
        
        // Enumerates all the items in the pager...
        for (int i=0; i<pager.Controls.Count; i+=2) {
            WebControl c = (WebControl)pager.Controls[i];
            if (c.GetType().ToString() == 
                "System.Web.UI.WebControls.DataGridLinkButton")
            c.CssClass = "PagerLink";
        }
    }
}