Freigeben über


Retrieving Data with a DbDataAdapter 

The DbProviderFactory lets you create provider-agnostic data adapters to work with data from any data source.

Fill a DataGrid by Using a DbDataAdapter

The CreateDataAdapter method of a DbProviderFactory object gives you a DbDataAdapter object that is strongly-typed to the underlying provider specified at the time you create the factory. The following code fragment creates a DbDataAdapter and fills a DataGrid control on an ASP.NET page. Although this example could easily have been written using strongly-typed objects directly, it demonstrates how you can use the data factory to retrieve the strongly-typed objects based on a provider name specified at runtime.

DbProviderFactory dataFactory = 
 DbProviderFactories.GetFactory("System.Data.SqlClient");
DbDataAdapter da = dataFactory.CreateDataAdapter();
da.SelectCommand = conn.CreateCommand();
da.SelectCommand.CommandText = 
  "SELECT SalesOrderID, OrderDate FROM SalesOrderHeader" 
  + " WHERE CustomerID=" + CustID.ToString();

// Fill the DataTable and bind the DataGrid
DataTable dt = new DataTable();
da.Fill(dt);
gridOrders.DataSource = dt;
gridOrders.DataBind();
Dim dataFactory As DbProviderFactory = _
 DbProviderFactories.GetFactory("System.Data.SqlClient")
Dim da As DbDataAdapter = dataFactory.CreateDataAdapter()
da.SelectCommand = conn.CreateCommand()
da.SelectCommand.CommandText = _
  "SELECT SalesOrderID, OrderDate FROM Sales.SalesOrderHeader" & _
  " WHERE CustomerID=" + CustID.ToString()

' Fill the DataTable and bind the DataGrid
Dim dt As New DataTable()
da.Fill(dt)
gridOrders.DataSource = dt
gridOrders.DataBind()

See Also

Concepts

Working with Factories
Provider Independent Model Overview
Obtaining the DbProviderFactory
Creating Commands and Retrieving Data