Using the DB2DataSource
The DB2DataSource enables you to use a single Web control to connect to DB2 and query data. By binding the control to other controls such as the GridView or ListBox, you can display, edit, and save DB2 data in an ASP.NET page. You can use the Visual Studio Designer to initialize the control, visually build queries, and bind controls; you can also define SQL commands from page code. The examples below show both approaches and use the GridView control as an example.
To use the DB2DataSource, add a reference to System.Data.CData.DB2.Web.dll in your ASP.NET project.
Bind Data Programmatically
The following example shows how to bind the results of a DB2 query to an ASP.NET data grid. After registering the assembly for use with the DB2DataSource, set the DataSourceID field of the GridView control to the Id of the DB2DataSource control:
<%@ Register Assembly="System.Data.CData.DB2.Web" Namespace="System.Data.CData.DB2" TagPrefix="cc1" %> ... <cc1:DB2DataSource Id="DB2DataSource1" runat="server" ConnectionString="Server=10.0.1.2;Port=50000;User=admin;Password=admin;Database=test" SelectCommand="SELECT * FROM \"Sample\".\"DB2INST1\".Books WHERE Category = 'US' LIMIT 10"></cc1:DB2DataSource> <asp:GridView DataSourceID="DB2DataSource1" runat="server"></asp:GridView>
Bind Data Using the Designer
Complete the following steps to use the Designer in Visual Studio to bind the DB2DataSource to a GridView control:
- Drag a GridView from the Toolbox onto the page.
- Click the Smart Tag of the GridView.
- Choose the option to create a new data source, which launches a wizard to configure the control.
- On the first page, select a connection string from the menu or click New Connection to define a new connection or to save a connection entry in the Web.config file.
- On the next page, select the option to define a SQL statement or visually build the query.
When you exit the wizard, the GridView displays the columns of the result set.