8.5. Binding Data to a Web Forms DataList Control

Problem

You need to bind the result set from a query to a DataList control and update the data source with changes, deletions, and new records using the DataList.

Solution

Follow the techniques demonstrated by this solution:

  1. The solution uses a table named DataList in the AdoDotNet35Cookbook database. Execute the following T-SQL statement to create the table:

    	USE AdoDotNet35Cookbook
    	GO
    	CREATE TABLE DataList(
    	    Id int NOT NULL PRIMARY KEY,
    	    IntField int NULL,
    	    StringField nvarchar(50) NULL )

    The schema of table DataList that is used in the solution is shown in Table 8-4.

    Table 8-4. DataList table schema

    Column name

    Data type

    Length

    Allow nulls?

    Id

    int

    4

    No

    IntField

    int

    4

    Yes

    StringField

    nvarchar

    50

    Yes

  2. Execute the following T-SQL batch to create the sample data needed for the solution.

    	USE AdoDotNet35Cookbook
    	GO
    	INSERT INTO DataList VALUES (1, 10, 'StringValue1')
    	INSERT INTO DataList VALUES (2, 20, 'StringValue2')
    	INSERT INTO DataList VALUES (3, 30, 'StringValue3')
    	INSERT INTO DataList VALUES (4, 40, 'StringValue4')
  3. Create a C# ASP.NET web application named BindWebFormDataList.

  4. Add the following controls to the Default.aspx design surface:

    • DataList named dataList

    • Button named insertButton with Text property = Insert

    The competed layout of the Web Form page Default.aspx is shown in Figure 8-9.

Layout for Default.aspx in BindWebFormDataList solution

Figure 8-9. Layout for Default.aspx in BindWebFormDataList solution

The code ...

Get ADO.NET 3.5 Cookbook, 2nd Edition 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.