O'Reilly logo

ADO.NET Cookbook by Bill Hamilton

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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

int

4

No

IntField

int

4

Yes

StringField

nvarchar

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

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required