对于大部分原来编写ASP程序的程序员来说,他们对ADO Recordset还是很有感情的。虽然在.NET里已经用DATSET代替了ADO Recordset,但是ADO Recordset在处理一些接口程序的时候还是很有用处的,尤其是当我们在.NET里调用返回ADO Recordset类型的COM时。当你看完下面的说明以后,你会发现它是如此EASY。效果如下图所示:
这里我们用到了a DataGrid and a DropDownList,他们帮定到相同的数据源。数据源是基于Northwind 数据库的。事实上,我们并不能直接绑定ASP.NET控件到ADO Recordset,我们需要添加一个 引用:ADODB library 。在我们的工程References 文件夹点击右键,选择添加引用,选择COM 页,加入Microsoft ActiveX Data Objects 2.7 Library。具体的代码如下:
private void Bind()
{
OleDbDataAdapter custDA = new OleDbDataAdapter();
DataTable dtTerritories = new DataTable("Territories");
ADODB.Connection adoConn = new ADODB.Connection();
ADODB.Recordset adoRS = new ADODB.Recordset();
adoConn.Open("Provider=SQLOLEDB;Data Source=localhost;Initial Catalog=Northwind;User Id=;Password=;", "", "", -1);
adoRS.Open("SELECT TerritoryID, TerritoryDescription FROM Territories Order By TerritoryDescription", adoConn, ADODB.CursorTypeEnum.adOpenForwardOnly, ADODB.LockTypeEnum.adLockReadOnly, 1);
custDA.Fill(dtTerritories, adoRS);
adoRS.Close();
adoConn.Close();
adoRS = null;
adoConn = null;
DataGrid1.DataSource = dtTerritories;
DataGrid1.DataBind();
DropDownList1.DataSource = dtTerritories;
DropDownList1.DataValueField = "TerritoryID";
DropDownList1.DataTextField = "TerritoryDescription";
DropDownList1.DataBind();
}