Tải bản đầy đủ (.pdf) (80 trang)

Assembly Language: Step-by-Step - part 6 ppt

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (1.81 MB, 80 trang )

Figure 6.5 The style hierarchy for the DataList and the DataGrid controls. Styles are
applied from the top to the bottom.
In the next series of DataList examples, the following code will be assigned
to the Page_Load method:
Private Sub Page_Load(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles MyBase.Load
Dim a As New ArrayList()
a.Add(New Employee(1, “GlennLast”, “Glenn”, 50000))
a.Add(New Employee(2, “JoeLast”, “Joe”, 42000))
a.Add(New Employee(3, “MaryLast”, “Mary”, 31000))
a.Add(New Employee(4, “FrankLast”, “Frank”, 36000))
a.Add(New Employee(5, “AnneLast”, “Anne”, 24000))
DataList1.DataSource = a
DataBind()
End Sub
Control Style
backcolor=style; font=arial
backcolor=silver; font=arial
Effective StyleStyle Hierarchy
backcolor=silver; font=arial;
font-bold=true
backcolor=silver; font=arial;
font-italic=true
backcolor=red; font=arial
backcolor=red; font=arial;
font-bold=true
Item: backcolor=yellow;
font=arial; font-bold=false
Alternate: backcolor=yellow;
font=arial; font-bold=true
Item: backcolor=yellow;


font=system; font-bold=false
Alternate: backcolor=yellow;
font=system; font-bold=true
Header Style
font-bold=true
Footer Style
font-italic=true
Item Style
backcolor=red
Alternating Item Style
font-bold-true
Selected Item Style
backcolor=yellow
Edit Item Style
font=system
208 Chapter 6
h 430234 Ch06.qxd 7/1/03 9:01 AM Page 208
This code uses the Employee class that was used in the previous Repeater
examples, and five Employee instances are being added to an ArrayList. In
this example, the DataList is placed on to the Web page and the fields are
placed into the item template as follows.
<asp:DataList id=DataList1 runat=”server”>
<itemtemplate>
<%# string.Format(“{0:D4}”,Container.DataItem.EID ) %>
<%# DataBinder.Eval(Container.DataItem, “LastName”)%>
<%# DataBinder.Eval(Container.DataItem, “FirstName”)%>
<%# DataBinder.Eval(Container.DataItem, “Salary”,”{0:C}”)%>
</ItemTemplate>
</asp:DataList>
The browser output (see the left window in Figure 6.6) shows a line for each

employee. Taking a peek at the browser’s source code reveals that the DataList
generated a table with one cell for each of the employees.
Figure 6.6 Shows a line (left) for each employee and then (right) shows a cleaner version,
with a table embedded into the item template.
Using Data-Bound Web Controls 209
h 430234 Ch06.qxd 7/1/03 9:01 AM Page 209
In the next example, some formatting is added by placing a table inside the
item template, as shown in the following code:
<asp:DataList id=DataList1 runat=”server”>
<itemtemplate>
<table>
<tr><td>Employee ID:</td>
<td><b><%# string.Format(“{0:D4}”,Container.DataItem.EID ) %></b>
</td></tr>
<tr><td>Employee Name: </td>
<td><b><%# DataBinder.Eval(Container.DataItem, “LastName”)%>,
<%# DataBinder.Eval(Container.DataItem, “FirstName”)%></b>
</td></tr>
<tr><td>Salary: </td>
<td><b>
<%# DataBinder.Eval(Container.DataItem, “Salary”,”{0:C}”)%>
</b></td></tr>
</table>
</ItemTemplate>
</asp:DataList>
This code will nest a table inside each of the cells that the DataList originally
produced. The browser output (see the right window in Figure 6.6) shows a
much cleaner appearance.
Although the last example was cleaner looking, it lacks a header, and it can
be difficult to see where one employee ends and another employee starts. In

the following example, an alternate item style is created. This is better than the
Repeater, because the layout from the item template does not need to be
copied. A header and footer are supplied here as well.
<asp:DataList id=DataList1 runat=”server”>
<headerstyle backcolor=”black”
forecolor=”white”
font-bold=”True”
horizontalalign=”Center”>
</headerstyle>
<alternatingitemstyle backcolor=”silver”>
</alternatingitemstyle>
<footerstyle backcolor=”black”
forecolor=”white”
font-bold=”True”
horizontalalign=”Center”>
</footerstyle>
<headertemplate>
Employee List
</headertemplate>
<itemtemplate>
<table>
210 Chapter 6
h 430234 Ch06.qxd 7/1/03 9:01 AM Page 210
<tr><td>Employee ID:</td>
<td><b>
<%# string.Format(“{0:D4}”,Container.DataItem.EID ) %>
</b>
</td></tr>
<tr><td>Employee Name: </td>
<td><b>

<%# DataBinder.Eval(Container.DataItem, “LastName”)%>,
<%# DataBinder.Eval(Container.DataItem, “FirstName”)%>
</b>
</td></tr>
<tr><td>Salary: </td>
<td><b>
<%# DataBinder.Eval(Container.DataItem, “Salary”,”{0:C}”)%>
</b></td></tr>
</table>
</ItemTemplate>
<footertemplate>
End of List
</footertemplate>
</asp:DataList>
The browser output (see Figure 6.7) shows a very readable list of employees.
The data is in the item template, and the formatting is in the style elements.
Figure 6.7 A much cleaner list of employees, with a header, a footer, and an alternating
style.
Using Data-Bound Web Controls 211
h 430234 Ch06.qxd 7/1/03 9:01 AM Page 211
Figure 6.8 The effect of setting the RepeatColumns to 3, the RepeatDirection to Horizontal,
the GridLines to Both, and the BorderColor to Black.
As the list of employees gets longer, it will be necessary to come up with a
way to fill the screen with employees instead of having a narrow column of
employees. That is where the RepeatColumns and RepeatDirection come into
play.
Figure 6.8 shows an example of setting the RepeatColumns to three and the
RepeatDirection to Horizontal. In this example, the GridLines property is set
to Both and the BorderColor is set to Black. Notice that the RepeatDirection
can also be set to Vertical, which will cause the employee list to be rendered

downward in vertical columns.
Selecting an Item
The DataList can allow a user to select an item. This is usually desirable when
only a small amount of data is being displayed and more details are desired.
Making a selection involves setting the SelectedIndex to a number other
than minus one (-1), which is the default. This can be done by creating an Item-
Command method, which will change the selection number.
There is one small problem, which is that the SelectedIndex must be set
before the data is bound to the DataList. Currently, our data is being bound in
the Page_Load method. This is only acceptable when the data is not being
posted to the server (the first time to the page). The code to create the employ-
ees will be placed into a procedure called BindEmployees as follows:
Private Sub Page_Load(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles MyBase.Load
If Not IsPostBack() Then
BindEmployees()
End If
End Sub
212 Chapter 6
h 430234 Ch06.qxd 7/1/03 9:01 AM Page 212
Public Sub BindEmployees()
Dim a As New ArrayList()
a.Add(New Employee(1, “GlennLast”, “Glenn”, 50000))
a.Add(New Employee(2, “JoeLast”, “Joe”, 42000))
a.Add(New Employee(3, “MaryLast”, “Mary”, 31000))
a.Add(New Employee(4, “FrankLast”, “Frank”, 36000))
a.Add(New Employee(5, “AnneLast”, “Anne”, 24000))
DataList1.DataSource = a
DataList1.DataBind()
End Sub

An event method must be created in the code-behind page to set the Selected-
Index of the DataList when a button is clicked. Do this by clicking the Class
Name drop-down list and clicking DataList1. In the Method drop-down list,
click ItemCommand, which inserts code for this event. In this method, add
code to set the SelectedIndex and call the BindEmployees method as follows:
Private Sub DataList1_ItemCommand(ByVal source As Object, _
ByVal e As System.Web.UI.WebControls.DataListCommandEventArgs) _
Handles DataList1.ItemCommand
DataList1.SelectedIndex = e.Item.ItemIndex
BindEmployees()
End Sub
Another event method must be added in the code-behind page to clear the
SelectedIndex when no details are desired. Do this by clicking the Class Name
drop-down list and then clicking DataList1. In the Method drop-down list,
click CancelCommand, which inserts code for the event. In this method, add
code to set the SelectedIndex to minus one (-1) and call the BindEmployees
method as follows:
Private Sub DataList1_CancelCommand(ByVal source As Object, _
ByVal e As System.Web.UI.WebControls.DataListCommandEventArgs) _
Handles DataList1.CancelCommand
DataList1.SelectedIndex = -1
BindEmployees()
End Sub
Finally, the item template is modified to display a Display Details button
and the employee’s full name. The selected item template contains all the
details plus a Hide Details button. The following code contains the completed
DataList1 control:
<asp:datalist id=DataList1 runat=”server”
GridLines=”Both”
bordercolor=”black” >

<headertemplate>
Employee List
</HeaderTemplate>
Using Data-Bound Web Controls 213
430234 Ch06.qxd 7/8/03 1:49 PM Page 213
<alternatingitemstyle backcolor=”Silver”>
</AlternatingItemStyle>
<selecteditemstyle backcolor=”yellow”>
</selecteditemstyle>
<footertemplate>
End of List
</FooterTemplate>
<selecteditemtemplate>
<table>
<tr><td colspan=”2”>
<asp:linkbutton id=”Linkbutton2” runat=”server”
text=”Hide Details” commandname=”cancel” />
</td></tr>
<tr><td>Employee ID:</td>
<td><b>
<%# string.Format(“{0:D4}”,Container.DataItem.EID ) %>
</b>
</td></tr>
<tr><td>Employee Name: </td>
<td><b>
<%# DataBinder.Eval(Container.DataItem, “LastName”)%>,
<%# DataBinder.Eval(Container.DataItem, “FirstName”)%>
</b>
</td></tr>
<tr><td>Salary: </td>

<td><b>
<%# DataBinder.Eval(Container.DataItem, “Salary”,”{0:C}”)%>
</b></td></tr>
</table>
</selecteditemtemplate>
<itemtemplate>
<table>
<tr><td colspan=”2”>
<asp:linkbutton id=”LinkButton1” runat=”server”
text=”Show Details” commandname=”select” />
</td></tr>
<tr><td>Employee Name: </td>
<td><b>
<%# DataBinder.Eval(Container.DataItem, “LastName”)%>,
<%# DataBinder.Eval(Container.DataItem, “FirstName”)%>
</b>
</td></tr>
</table>
</ItemTemplate>
<footerstyle font-bold=”True” horizontalalign=”Center”
forecolor=”White” backcolor=”Black”>
</FooterStyle>
<headerstyle font-bold=”True” horizontalalign=”Center”
forecolor=”White” backcolor=”Black”>
</HeaderStyle>
</asp:datalist>
214 Chapter 6
h 430234 Ch06.qxd 7/1/03 9:01 AM Page 214
Figure 6.9 Employee list with no employee details selected (left) and with employee
0003 selected (right).

The browser output (see Figure 6.9) shows the items without and with an
employee selected. If the Show Details is clicked on a different employee, that
employee’s details are exposed.
Editing an Item
The DataList can allow a user to edit an item. Editing an item involves setting
the EditItemIndex to a number other than minus one (-1), which is the default.
This can be done by creating an EditCommand method, which will change the
edit item number.
There is one small problem: Our data in the ArrayList is not persisted, so the
ArrayList is being recreated every time that data is posted back to the server.
The BindEmployee method has been changed to store the ArrayList in a Ses-
sion variable. Session variables are available throughout the browser session
and will be covered in more detail in Chapter 12, “ASP.NET Applications.”
The following is the revised BindEmployees method:
Public Sub BindEmployees()
‘create employee list if it
‘does not exist
If Session(“Employees”) Is Nothing Then
Dim a As New ArrayList()
a.Add(New Employee(1, “GlennLast”, “Glenn”, 50000))
a.Add(New Employee(2, “JoeLast”, “Joe”, 42000))
a.Add(New Employee(3, “MaryLast”, “Mary”, 31000))
a.Add(New Employee(4, “FrankLast”, “Frank”, 36000))
a.Add(New Employee(5, “AnneLast”, “Anne”, 24000))
Using Data-Bound Web Controls 215
h 430234 Ch06.qxd 7/1/03 9:01 AM Page 215
Session(“Employees”) = a
End If
DataList1.DataSource = Session(“Employees”)
DataList1.DataBind()

End Sub
An event method must be created in the code-behind page to set the Edit-
ItemIndex of the DataList when a button is clicked. Do this by clicking the Class
Name drop-down list and then clicking DataList1. In the Method drop-down
list, click EditCommand, which inserts code for this event. In this method, add
code to set the EditItemIndex, and call the BindEmployees method as follows:
Private Sub DataList1_EditCommand(ByVal source As Object, _
ByVal e As System.Web.UI.WebControls.DataListCommandEventArgs) _
Handles DataList1.EditCommand
DataList1.EditItemIndex = e.Item.ItemIndex
BindEmployees()
End Sub
The CancelCommand must be modified to set the EditItemIndex to minus
one (-1) if editing is cancelled:
Private Sub DataList1_CancelCommand(ByVal source As Object, _
ByVal e As System.Web.UI.WebControls.DataListCommandEventArgs) _
Handles DataList1.CancelCommand
If DataList1.EditItemIndex = -1 Then
DataList1.SelectedIndex = -1
Else
DataList1.EditItemIndex = -1
End If
BindEmployees()
End Sub
The selected item template has been changed to have an Edit button beside
the Hide Details button. Also, an edit item template needs to be added to the
DataList. The following is the revised selected item template and the new edit
item template:
<selecteditemtemplate>
<table>

<tr>
<td>
<asp:linkbutton id=”itemCancel” runat=”server”
text=”Hide Details” commandname=”cancel” />
</td>
<td>
<asp:linkbutton id=”itemEdit” runat=”server”
text=”Edit” commandname=”edit” />
</td>
</tr>
216 Chapter 6
h 430234 Ch06.qxd 7/1/03 9:01 AM Page 216
<tr><td>Employee ID:</td>
<td><b>
<%# string.Format(“{0:D4}”,Container.DataItem.EID ) %>
</b>
</td></tr>
<tr><td>Employee Name: </td>
<td><b>
<%# DataBinder.Eval(Container.DataItem, “LastName”)%>,
<%# DataBinder.Eval(Container.DataItem, “FirstName”)%>
</b>
</td></tr>
<tr><td>Salary: </td>
<td><b>
<%# DataBinder.Eval(Container.DataItem, “Salary”,”{0:C}”)%>
</b></td></tr>
</table>
</SelectedItemTemplate>
<edititemtemplate>

<table>
<tr>
<td>
<asp:linkbutton id=”editCancel” runat=”server”
text=”Cancel” commandname=”cancel” />
</td>
<td>
<asp:linkbutton id=”editUpdate” runat=”server”
text=”Update” commandname=”update” />
</td>
</tr>
<tr><td>Employee ID:</td>
<td><b>
<asp:label id=”empID” runat=”server”
Text=’<%# string.Format(“{0:D4}”,Container.DataItem.EID ) %>’ />
</b>
</td></tr>
<tr><td>Last: </td>
<td>
<asp:textbox id=”empLast” runat=”server”
Text=’<%# DataBinder.Eval(Container.DataItem, “LastName”)%>’ />
</td></tr>
<tr><td>First: </td>
<td>
<asp:textbox id=”empFirst” runat=”server”
Text=’<%# DataBinder.Eval(Container.DataItem, “FirstName”)%>’ />
</td></tr>
<tr><td>Salary: </td>
<td>
<asp:textbox id=”salary” runat=”server”

Text=’<%# DataBinder.Eval(Container.DataItem, “Salary”)%>’ />
</td></tr>
</table>
</edititemtemplate>
Using Data-Bound Web Controls 217
h 430234 Ch06.qxd 7/1/03 9:01 AM Page 217
Figure 6.10 The DataList with an employee selected (left) and with the employee in edit
mode (right).
The browser output is shown in Figure 6.10. Notice that the edit item tem-
plate contains TextBoxes for the editable fields. The employee ID field is a
read-only field, so it is displayed in a Label control.
The last thing to do is to update the data. The update will be very different,
based on the data source. To do any update, the data must be retrieved from
the edit template. This can be done with the FindControl method. The follow-
ing code demonstrates the extraction of data from the edit template and the
updating of the employee data.
Private Sub DataList1_UpdateCommand(ByVal source As Object, _
ByVal e As System.Web.UI.WebControls.DataListCommandEventArgs) _
Handles DataList1.UpdateCommand
Dim empID As Label = e.Item.FindControl(“empID”)
Dim empLast As TextBox = e.Item.FindControl(“empLast”)
Dim empFirst As TextBox = e.Item.FindControl(“empFirst”)
Dim salary As TextBox = e.Item.FindControl(“salary”)
‘This would normally be an
‘update statement to the database
Dim emp As Employee
For Each emp In Session(“Employees”)
If emp.EID = Integer.Parse(empID.Text) Then
emp.LastName = empLast.Text
emp.FirstName = empFirst.Text

emp.Salary = Decimal.Parse(salary.Text)
Exit For
End If
218 Chapter 6
h 430234 Ch06.qxd 7/1/03 9:01 AM Page 218
Next
DataList1.EditItemIndex = -1
BindEmployees()
End Sub
The DataList can also be set up by using the GUI menus. These menus are
available by right-clicking the DataList, and then clicking Auto Format,
Property Builder, or Edit Template.
DataGrid Control
The DataGrid control is the most powerful of the data bound controls pro-
vided with ASP.NET. The DataGrid is designed to display the fields of a data
source in an HTML table. Each row in the HTML table represents one of the
repeating items in the data source.
The DataGrid supports item selection, editing, deleting, sorting, and pag-
ing. The DataGrid has many properties, but can be quickly set up to display
data by using its default settings. The DataGrid provides the following prop-
erties that have already been defined in this chapter and can be set in the
Visual Studio .NET designer or in code:
■■
DataSource
■■
DataMember
In addition, the DataGrid contains several properties that have not yet been
defined. Table 6.5 contains the list of new properties.
Table 6.5 Additional DataGrid Properties
PROPERTY DESCRIPTION

AllowCustomPaging Changeable Boolean value indicating whether custom
paging is used. If custom paging is used, the
assumption is that the data source does not contain
all of the data. The data source instead contains only
one page of data.
AllowPaging Changeable Boolean value indicating whether paging
is allowed. Paging allows data to be split into smaller
segments based on the PageSize property.
AllowSorting Changeable Boolean value indicating whether sorting
is enabled. If the value is true, LinkButtons controls
are rendered in the header of each column that has
its SortExpression property set.
(continued)
Using Data-Bound Web Controls 219
h 430234 Ch06.qxd 7/1/03 9:01 AM Page 219
Table 6.5 (continued)
PROPERTY DESCRIPTION
AutoGenerateColumns Changeable Boolean property indicating whether
columns will be automatically generated and
rendered. If true, a column will be created for each
field in the data source. Columns may also be
explicitly added, and they will appear before the
autogenerated columns.
BackImageUrl Changeable value containing the location of the
image that is used as a background for the DataGrid.
The image will tile as necessary to fill the DataGrid.
Columns Changeable value containing a
DataGridColumnCollection. Note that autogenerated
columns will not be added to this collection.
CurrentPageIndex Changeable value containing the page of data that

will display in the DataGrid.
EditItemIndex Changeable value indicating which item in the
DataGrid is being edited. This value is set to -1 when
no item is being edited.
Items Changeable value containing the items from the data
source that are included in the DataGrid.
PageCount Read-only count of the quantity of pages that are
required to display all of the data.
PagerStyle Changeable value indicating the type of paging
controls that will be rendered onto the DataGrid. The
PageStyle mode can be set to Numeric, to display page
number links for each page, or to PrevNext to display
previous and next links to move between pages.
PageSize Changeable value containing the count of rows per
DataGrid page.
SelectedIndex Changeable value indicating the currently selected
item in the DataGrid. This value is set to -1 when no
item is selected.
SelectedItem Read-only value that contains the row that is currently
selected in the DataGrid.
ShowHeader Changeable Boolean value indicating whether the
header should be displayed.
ShowFooter Changeable Boolean value indicating whether the
footer should be displayed.
VirtualItemCount Changeable value containing the virtual quantity of
items for use when using custom paging.
220 Chapter 6
h 430234 Ch06.qxd 7/1/03 9:01 AM Page 220
In the next series of DataGrid examples, the following code will be assigned
to the Page_Load method and the BindEmployees method:

Private Sub Page_Load(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles MyBase.Load
If Not IsPostBack() Then
BindEmployees()
End If
End Sub
Public Sub BindEmployees()
‘Create employee list if it
‘does not exist.
If Session(“Employees”) Is Nothing Then
Dim a As New ArrayList()
a.Add(New Employee(1, “GlennLast”, “Glenn”, 50000))
a.Add(New Employee(2, “JoeLast”, “Joe”, 42000))
a.Add(New Employee(3, “MaryLast”, “Mary”, 31000))
a.Add(New Employee(4, “FrankLast”, “Frank”, 36000))
a.Add(New Employee(5, “AnneLast”, “Anne”, 24000))
Session(“Employees”) = a
End If
DataGrid1.DataSource = Session(“Employees”)
DataGrid1.DataBind()
End Sub
The code is using the Employee class that was used in the previous Repeater
and DataList examples, and five Employee instances are added to an
ArrayList. In this example, the DataGrid is placed on to the Web page.
When the page is displayed (see Figure 6.11), the DataGrid created and ren-
dered three columns. Notice that the employee ID (EID) of the employees has
not been rendered, because the DataGrid is not looking for public fields; it’s
only looking for public properties.
Assigning a Style to the DataGrid
The DataGrid supports style elements, which allows the style to change with-

out repeating the same code. For example, the Repeater control examples in this
chapter had the same code for the ItemTemplate and the AlternatingItem-
Template. The only thing that was different was the style.
The DataGrid solves the problem with these special style elements. The fol-
lowing is a list of style elements that are supported by the DataGrid. Figure 6.5
shows the style hierarchy.
■■
AlternatingItemStyle
■■
EditItemStyle
■■
FooterStyle
■■
HeaderStyle
Using Data-Bound Web Controls 221
h 430234 Ch06.qxd 7/1/03 9:01 AM Page 221
■■
ItemStyle
■■
SelectedItemStyle
In addition to these styles, a quick way to assign a style is to right-click the
DataGrid and then click Auto Format. The Auto Format window displays
many options that allow the DataGrid to be quickly formatted. Professional 3
will be used in the following examples, as shown in Figure 6.11.
Adding Columns to the DataGrid
You can add columns to the DataGrid via HTML, code, or the Property
Builder. The following types of columns may be added to the DataGrid:
BoundColumn. A column that can be bound to a field in the data source.
ButtonColumn. A column that contains a command button. This button
can be used with the item on the current row (for example, Add or

Delete).
EditCommandColumn. A column that displays an Edit button until a
row is being edited. When a row is being edited, Cancel and Update but-
tons will be placed in the column on the edited row.
HyperLinkColumn. A column that displays a hyperlink button, which
can be configured to provide a URL and a querystring that contains
information about the current item.
TemplateColumn. A column with the ability to be completely cus-
tomized with templates.
In the previous example, the employee ID column was missing. The follow-
ing code adds the employee ID to the DataGrid.
Private Sub DataGrid1_Init(ByVal sender As Object, _
ByVal e As System.EventArgs) _
Handles DataGrid1.Init
Dim col As New BoundColumn()
col.HeaderText = “Employee ID”
DataGrid1.Columns.Add(col)
End Sub
It is important to add the column as early as possible in the DataGrid con-
trol’s life cycle. Adding the column in the Init event method of the DataGrid
means that the column will be available to work with ViewState and be
assigned data.
Although a bound column was used, a DataField could not be provided
because the EID is a public variable instead of a property. Although this col-
umn will be displayed, there will not be any data.
222 Chapter 6
h 430234 Ch06.qxd 7/1/03 9:01 AM Page 222
Figure 6.11 DataGrid rendered with default settings (left), and with Professional 3 style
selected (right).
An easy way to populate the data would be to add code to the DataGrid’s

ItemDataBound event method. This method executes every time that a row
needs to be rendered. One problem is that this will execute on the header and
footer rows, so a check needs to be done to verify that there is data available
for a row before attempting to extract the EID. The following code will get the
EID and populate column 0, which is the Employee ID column.
Private Sub DataGrid1_ItemDataBound(ByVal sender As Object, _
ByVal e As System.Web.UI.WebControls.DataGridItemEventArgs) _
Handles DataGrid1.ItemDataBound
If TypeOf e.Item.DataItem Is Employee Then
Dim currentEmployee As Employee = _
CType(e.Item.DataItem, Employee)
e.Item.Cells(0).Text = _
string.Format(“{0:D3}”,currentEmployee.EID)
End If
End Sub
Using Data-Bound Web Controls 223
h 430234 Ch06.qxd 7/1/03 9:01 AM Page 223
This is one example method of populating the Employee ID column.
Another method of populating the Employee ID column is to use an object-
oriented approach as described in the sidebar titled Object-Oriented Method to
Display Hidden Data in a DataGrid.
224 Chapter 6
♦ Object-Oriented Method to Display Hidden
Data in a DataGrid
The Employee class was created with the EID, which is a public read-only member variable.
In the DataList and DataGrid examples, the public properties were displayed, while a more
creative method was required to get to the EID. In these examples, the source code for the
Employees class was available, so a simple way to get access to the EID would be to add
another public property to the Employee class.
How is this problem solved if the source code is unavailable? If the Employee class was

provided as a compiled .dll file with no source code, it’s not possible to simply add the
property. Instead, a new class can be created that inherits from the Employee class. The fol-
lowing code is an example of a new class called EmployeeData, which inherits from
Employee. This class has the additional read-only property called EmployeeID. The rest of
the properties are available through inheritance.
Public Class EmployeeData
Inherits Employee
Public Sub New(ByVal EID As Integer, _
ByVal LastName As String, _
ByVal FirstName As String, _
ByVal Salary As Decimal)
MyBase.New(EID, LastName, FirstName, Salary)
End Sub
Public ReadOnly Property EmployeeID() As Integer
Get
Return EID
End Get
End Property
End Class
This class could be used to create an EmployeeData collection instead of the Employee col-
lection. The EmployeeData collection could be assigned to the data source of the DataGrid.
430234 Ch06.qxd 7/8/03 1:49 PM Page 224
With the HTML page, the DataGrid tag can contain a columns collection.
Another method of adding the EID column is by adding a template column tag
in the DataGrid HTML tag. The following code is an example of the added
template column. This code is similar to the DataList template code:
<asp:DataGrid id=”DataGrid1” runat=”server”>
<columns>
<asp:TemplateColumn HeaderText=”Employee ID”>
<itemtemplate>

<%# string.Format(“{0:D4}”,Container.DataItem.EID ) %>
</ItemTemplate>
</asp:TemplateColumn>
</Columns>
</asp:DataGrid>
Visual Studio .NET also provides a property builder that can be used to
insert columns via GUI windows. The property builder can be accessed by
right-clicking the DataGrid and then clicking Property Builder. Figure 6.12
shows the Property Builder screen.
Figure 6.12 Most DataGrid properties may be assigned with the DataGrid Property
Builder.
Using Data-Bound Web Controls 225
h 430234 Ch06.qxd 7/1/03 9:01 AM Page 225
Ordering Columns
Although all columns may be displayed, the order of the fields may not be
appropriate. In addition, different header text may be required. In the previous
example, the fields were automatically added, but it’s usually better to manu-
ally create the columns and set their properties. Once again, the columns may
be added manually via code, the HTML window, or the Property Builder. All
of the examples that follow are done in code.
The columns need to be added to the DataGrid’s Init event method. In the
following code example, all four columns are manually added in the appro-
priate order and with the desired header text.
Private Sub DataGrid1_Init(ByVal sender As Object, _
ByVal e As System.EventArgs) _
Handles DataGrid1.Init
DataGrid1.AutoGenerateColumns = False
Dim col As New BoundColumn()
col.HeaderText = “Employee<BR>ID”
col.ItemStyle.HorizontalAlign = HorizontalAlign.Right

col.HeaderStyle.HorizontalAlign = HorizontalAlign.Center
col.ItemStyle.Width = New Unit(75, UnitType.Pixel)
DataGrid1.Columns.Add(col)
‘Store this info for later use.
DataGrid1.Attributes(“EidCol”) = DataGrid1.Columns.Count - 1
col = New BoundColumn()
col.HeaderText = “Last<BR>Name”
col.DataField = “LastName”
col.HeaderStyle.HorizontalAlign = HorizontalAlign.Center
col.ItemStyle.Width = New Unit(200, UnitType.Pixel)
DataGrid1.Columns.Add(col)
DataGrid1.Attributes(“LastNameCol”) = _
DataGrid1.Columns.Count - 1
col = New BoundColumn()
col.HeaderText = “First<BR>Name”
col.DataField = “FirstName”
col.HeaderStyle.HorizontalAlign = HorizontalAlign.Center
col.ItemStyle.Width = New Unit(200, UnitType.Pixel)
DataGrid1.Columns.Add(col)
DataGrid1.Attributes(“FirstNameCol”) = _
DataGrid1.Columns.Count - 1
col = New BoundColumn()
col.HeaderText = “Salary”
col.DataField = “Salary”
col.DataFormatString = “{0:C}”
col.ItemStyle.HorizontalAlign = HorizontalAlign.Right
col.HeaderStyle.HorizontalAlign = HorizontalAlign.Center
col.ItemStyle.Width = New Unit(150, UnitType.Pixel)
DataGrid1.Columns.Add(col)
DataGrid1.Attributes(“SalaryCol”) = _

DataGrid1.Columns.Count - 1
End Sub
226 Chapter 6
h 430234 Ch06.qxd 7/1/03 9:01 AM Page 226
Private Sub DataGrid1_ItemDataBound(ByVal sender As Object, _
ByVal e As System.Web.UI.WebControls.DataGridItemEventArgs) _
Handles DataGrid1.ItemDataBound
Dim EidCol As Integer
EidCol = Integer.Parse(DataGrid1.Attributes(“EidCol”))
If TypeOf e.Item.DataItem Is Employee Then
Dim currentEmployee As Employee = _
CType(e.Item.DataItem, Employee)
e.Item.Cells(EidCol).Text = _
String.Format(“{0:D3}”, currentEmployee.EID)
End If
End Sub
Figure 6.13 shows the browser output. The first statement in this code
turned off the automatic generation of the columns. If this setting were not set
to false, the manual columns and the autogenerated columns would be dis-
played. The statements that follow set up each of the columns in order. Each
column has additional formatting to set the width of the column and the align-
ment of the text. The last part of the code is the ItemDataBound event method.
This only contains code to assign the employee ID, because the other columns
were easily bound by their field name in the InitDataBind method.
Another interesting item is the persistence of the column numbers. After the
column was added, the column number is persisted to an attribute in the Data-
Grid. This means that a peek at the browser source will reveal these attributes
on DataGrid1’s table. This attributes can be retrieved when binding, selecting,
editing, and updating the data. The benefit of this approach is realized when
more columns are added. There is no need to update the column numbers

throughout the code.
Figure 6.13 The browser output showing the DataGrid with its columns defined in the
code-behind page.
Using Data-Bound Web Controls 227
h 430234 Ch06.qxd 7/1/03 9:01 AM Page 227
Selecting an Item
The DataGrid can allow a user to select an item. This is usually desirable when
only a small amount of data is being displayed and more details are desired. A
common requirement is to cause a child DataGrid to refresh and display infor-
mation about the item that was selected in the parent DataGrid. For example,
selecting a customer may cause that customer’s orders to be displayed in a
child DataGrid.
Making a selection involves setting the SelectedIndex to a number other
than minus one (-1), which is the default. This can be done by creating an Item-
Command method, which will change the selection number. The SelectedIn-
dex must be set before the data is bound to the DataList. After the SelectedIndex
is set, a call will be made to bind the data.
The following code shows the addition of a column to the top of the Data-
Grid1 Init method and the added ItemCommand event method:
Private Sub DataGrid1_Init(ByVal sender As Object, _
ByVal e As System.EventArgs) _
Handles DataGrid1.Init
DataGrid1.AutoGenerateColumns = False
Dim colSelect As New ButtonColumn()
colSelect.ButtonType = ButtonColumnType.PushButton
colSelect.Text = “Select”
colSelect.CommandName = DataGrid.SelectCommandName
DataGrid1.Columns.Add(colSelect)
‘additional columns here as shown in
‘the previous example

End Sub
Private Sub DataGrid1_ItemCommand(ByVal source As Object, _
ByVal e As System.Web.UI.WebControls.DataGridCommandEventArgs) _
Handles DataGrid1.ItemCommand
DataGrid1.SelectedIndex = e.Item.ItemIndex
‘Get EID and simply display it.
Dim EidCol As Integer
EidCol = Integer.Parse(DataGrid1.Attributes(“EidCol”))
Dim EID As Integer
EID = Integer.Parse(e.Item.Cells(EidCol).Text)
Label1.Text = “Employee ID Selected: “ & EID.ToString()
BindEmployees()
End Sub
This code displays the EID of the selected employee in a Label control that
is placed on the page as shown in Figure 6.14.
228 Chapter 6
h 430234 Ch06.qxd 7/1/03 9:01 AM Page 228
Figure 6.14 The ItemCommand event has been used to retrieve the current employee ID
and display it in a Label control.
Editing an Item
The DataGrid can allow a user to edit an item. Editing an item involves setting
the EditItemIndex to a number other than minus one (-1), which is the default.
This is done by clicking the Class Name drop-down list and then clicking
DataGrid1. In the Method drop-down list, click EditCommand, which inserts
code for this event. In this method, add code to set the EditItemIndex and call
the BindEmployees method as follows:
Private Sub DataGrid1_EditCommand(ByVal source As Object, _
ByVal e As System.Web.UI.WebControls.DataGridCommandEventArgs) _
Handles DataGrid1.EditCommand
DataGrid1.EditItemIndex = e.Item.ItemIndex

BindEmployees()
End Sub
The CancelCommand must be modified to set the EditItemIndex to minus
one (-1) if editing is cancelled.
Private Sub DataGrid1_CancelCommand(ByVal source As Object, _
ByVal e As System.Web.UI.WebControls.DataGridCommandEventArgs) _
Handles DataGrid1.CancelCommand
DataGrid1.EditItemIndex = -1
BindEmployees()
End Sub
Using Data-Bound Web Controls 229
h 430234 Ch06.qxd 7/1/03 9:01 AM Page 229
The following code shows the addition of the Edit button column to the
DataGrid1 Init method. The Edit button turns into an Update and Cancel but-
ton pair when the Edit button is clicked. Figure 6.15 shows the new Edit col-
umn and the browser in edit mode.
Dim colEdit As New EditCommandColumn()
colEdit.ButtonType = ButtonColumnType.PushButton
colEdit.EditText = “Edit”
colEdit.CancelText = “Cancel”
colEdit.UpdateText = “Update”
colEdit.ItemStyle.Width = New Unit(200, UnitType.Pixel)
DataGrid1.Columns.Add(colEdit)
The Edit and Cancel code has been added. The last item to be added to the
program is the Update method. This is done by clicking the Class Name drop-
down list and then clicking DataGrid1. In the Method drop-down list, click
UpdateCommand, which inserts code for this event. The following code
updates the ArrayList that is stored in Session(“Employees”).
Private Sub DataGrid1_UpdateCommand(ByVal source As Object, _
ByVal e As System.Web.UI.WebControls.DataGridCommandEventArgs) _

Handles DataGrid1.UpdateCommand
Dim LastName As TextBox
Dim FirstName As TextBox
Dim Salary As TextBox
LastName = CType(e.Item.Cells(DataGrid1.Attributes( _
“LastNameCol”)).Controls(0), TextBox)
FirstName = CType(e.Item.Cells(DataGrid1.Attributes( _
“FirstNameCol”)).Controls(0), TextBox)
Salary = CType(e.Item.Cells(DataGrid1.Attributes( _
“SalaryCol”)).Controls(0), TextBox)
‘Get the row index from the DataGrid.
Dim di As Integer = e.Item.DataSetIndex
‘Get the Data from the DataGrid.
Session(“Employees”)(di).LastName = LastName.Text
Session(“Employees”)(di).FirstName = FirstName.Text
Session(“Employees”)(di).Salary = Salary.Text
‘Get EID and display it
Dim EidCol As Integer
EidCol = Integer.Parse(DataGrid1.Attributes(“EidCol”))
Dim EID As Integer
EID = Integer.Parse(e.Item.Cells(EidCol).Text)
Label1.Text = “Employee ID Updated: “ & EID.ToString()
DataGrid1.EditItemIndex = -1
BindEmployees()
End Sub
230 Chapter 6
h 430234 Ch06.qxd 7/1/03 9:01 AM Page 230
Figure 6.15 The new edit column (left) and the browser in edit mode (right).
In this code, references are first obtained to each of the TextBoxes that were
displayed. The attributes that were saved when the columns were added can

be used to select the appropriate cell. Retrieving Controls(0) gets the first con-
trol in the call, but it must be cast to a TextBox data type by using the CType
function. This allows access to the Text property.
Another interested property of the Item is the DataSetIndex, which contains
the row number of the data source. This can easily be used to assign the mod-
ified values to Session(“Employees”). The Item also contains an ItemIndex
property, which contains the index number of the current item in the Data-
Grid. This may not be equal to the DataSetRow, especially when paging is
used in the DataGrid.
The last piece of the update code retrieves the EID and places its value in
Label1. In these examples, the EID is considered read-only, so no attempt is
made to edit or update this field.
Using Data-Bound Web Controls 231
h 430234 Ch06.qxd 7/1/03 9:01 AM Page 231
Lab 6.1: Data Bound Web Controls
In this lab, you will work with the DataRepeater, DataList, and DataGrid
to display a collection of categories from the category classes that were
created in Lab 4.1.
Displaying the Categories in a Repeater
In this section, you will add a Repeater to the ProductList page.
1. Start this lab by opening the OrderEntrySolution from Lab 5.1.
2. Right-click the OrderEntrySolution in the Solution Explorer, and
then click Check Out. This will check out the complete solution.
3. Right-click the Inventory project, and then click Set as Startup
Project.
4. Right-click the ProductList.aspx page, and then click Set As Start
Page.
5. Open the ProductList.aspx page. Add a Repeater control to the
page. Rename the repeater to ProductGrid.
6. Click the HTML tab and add a header template to the ProductGrid

that displays Product List with a silver background. The font should
be in a large size and centered.
7. Add an item template to the ProductGrid to display the product
name, price, and quantity on hand. These items should be listed on
a separate line. Be sure to use the DataBinder.Eval method to dis-
play the price as a formatted currency value.
8. Add a separator template. In the separator template, add a horizon-
tal line.
9. Add a footer template that displays End of List with a silver back-
ground. The font should be xx-small size and centered. Your HTML
for the ProductsGrid should look like the following:
<asp:repeater id=ProductGrid runat=”server”>
<headertemplate >
<div style=”font-size: large;
background-color: silver; text-align: center”>
Product List
232 Chapter 6
h 430234 Ch06.qxd 7/1/03 9:01 AM Page 232

×