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"> ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access