7.3. Binding Data to a Web Forms DataList
Problem
You need to bind the result set from a query to a DataList
control.
Solution
Set the DataList
’s advanced
properties as demonstrated by this solution.
The schema of table TBL0703 that is used in the solution is shown in Table 7-2.
Table 7-2. TBL0703 schema
Column name |
Data type |
Length |
Allow nulls? |
---|---|---|---|
Id |
|
4 |
No |
IntField |
|
4 |
Yes |
StringField |
|
50 |
Yes |
The Web Forms page sample code defines the
DataList
control and the three
templates—SelectedItemTemplate
,
ItemTemplate
, and
EditItemTemplate
—which control the display
of data for selected items, unselected items, and items being edited.
The static Eval(
)
method of
the DataBinder
class is used to fill the field
values in each template. Container.DataItem
specifies the container
argument for the method
which when used in a list in a template resolves to
DataListItem.DataItem
. The code for the Web Forms
page is shown Example 7-5.
Example 7-5. File: ADOCookbookCS0703.aspx
<asp:DataList id="dataList" style="Z-INDEX: 102; LEFT: 16px; POSITION: absolute; TOP: 56px" runat="server"> <SelectedItemTemplate> <asp:Button id="editButton" runat="server" Text="Edit" CommandName="Edit"> </asp:Button> <B> <%# DataBinder.Eval(Container.DataItem, "Id") %>; <%# DataBinder.Eval(Container.DataItem, "IntField") %>; <%# DataBinder.Eval(Container.DataItem, "StringField") %> </B> </SelectedItemTemplate> <ItemTemplate> <asp:Button id="selectButton" runat="server" Text="Select" CommandName="Select"> ...
Get ADO.NET Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.