日期:2008-09-14  浏览次数:20451 次


这是一篇关于使用可重用代码绑定ADO数据到控件的文章。


介绍
ADO是一种功能非常强大的从数据库中读取数据的技术,但是它也使人很容易搞糊涂,连接数据到DataGrid或其他控件需要一些技巧和连接方法。我使用的方法是开发标准化的可重用代码访问数据库和显示数据。我已经写了很多通过SQL语句在DataGrid中显示结果的ASP.NET页面。

这篇文章将要描述我是怎样使用可重用代码连接ADO数据,并在DataGrid和其他控件中显示结果的。我也会讲述怎么为类似的任务开发你自己的代码。
背景
这篇文章假定你已经具有C#,SQL,ADO和.NET控件的知识。

我在演示代码中使用的是NorthWind数据库,但是你可以使用任意的数据库。
使用代码Web.Config
我使用在 web.config 中的 <appSettings> 来保存程序中所要用到的字符串。如果你没这样做过,那么你应该试一试。我一般使用 web.config 保存数据库连接信息,因为这样可以使它更具有可移植性。

 <appSettings>



  <add key="dsn_SQL"



    value="SERVER=localhost;uid=myuser;password=pass;DATABASE=NorthWind;"/>



</appSettings>


DataGrid.aspx.cs
下面使 DataGrid.aspx 页面的完整代码。在这个程序中 BindGrid() 函数的作用使连接到数据库并在 DataGrid 中显示结果数据。

using System;



using System.Collections;



using System.ComponentModel;



using System.Data;



using System.Drawing;



using System.Web;



using System.Web.SessionState;



using System.Web.UI;



using System.Web.UI.WebControls;



using System.Web.UI.HtmlControls;



using System.Data.SqlClient;



using System.Configuration;




 


namespace Easy_ADO_Binds



{



  public class WebForm1 : System.Web.UI.Page



  {



    protected System.Web.UI.WebControls.DataGrid DataGrid1;



    // 从 web.config 获得连接字符串



    public String strConnectSQL =



      (ConfigurationSettings.AppSettings["dsn_SQL"]);




 


    private void Page_Load(object sender, System.EventArgs e)



    {



      // 构造SQL字符串



      string SQLstring = "Select * FROM Employee";




 


      // 调用并构造BindGrid



      BindGrid(strConnectSQL, SQLstring, DataGrid1 );



    }




 


    private void BindGrid(string DBconnectString, string sqlCommand,



                           System.Web.UI.WebControls.DataGrid DGrid)



// 从数据库中加载初始化页面



// 绑定到datagrid



    {



      // 创建数据连接



      SqlConnection conn = new SqlConnection(DBconnectString);




 


      // 调用SQL语句



      SqlCommand command = new SqlCommand(sqlCommand, conn);




 


      // 创建data adapter



      SqlDataAdapter adapter = new SqlDataAdapter(command);




 


      // 创建并填充dataset



      DataSet ds = new DataSet();



      adapter.Fill(ds);




 


      // 填充并绑定到datagrid



      DGrid.DataSource = ds;



      DGrid.DataBind();



      // 关闭连接



      conn.Close();



    }




 


#region Web Form Designer generated code



    override protected void OnInit