您的位置:首页 > 运维架构

【翻译】在DataGrids和DropDownLists中使用ADO

2005-03-10 13:50 239 查看
原文出处:http://www.codeproject.com/aspnet/EasyADODgrids.aspDataGridsDropDownLists中使用ADO作者:knarf_scot 这是一篇关于使用可重用代码绑定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.DataGridDataGrid1;
    // 从 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(stringDBconnectString,stringsqlCommand,
                           System.Web.UI.WebControls.DataGridDGrid)
// 从数据库中加载初始化页面
// 绑定到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(EventArgs e)
    {
      //
      // CODEGEN: This call is required by the ASP.NET Web Form Designer.
      //
      InitializeComponent();
      base.OnInit(e);
    }
    private void InitializeComponent()
    {
      this.Load += new System.EventHandler(this.Page_Load);
    }
#endregion
  }
}

从 Web.Config 获得SQL字符串

允许你从 web.config 拿出你所需要的字符串,这是不是很灵活?我用这种方法指定数据库的连接,报告服务器,主页默认URL字符串以及其他一些全局性的字符串。
using System.Configuration;
// web.config 获得连接字符串
public String strConnectSQL = (ConfigurationSettings.AppSettings["dsn_SQL"]);

private void BindGrid()

这时工程最后做的事情。我把这些代码放到任意的页面中,我希望能从自己的数据库中取到数据并用
DataGrid
显示出来。我不必写复杂的C#或ADO代码。随便访问它,通过数据库、SQL、
DataGrid
参数,就为我获得了数据。

BindGrid() 如何工作

你传递给
BindGrid()
一个数据库连接,一个SQL字符串和一个
DataGrid
标识符,然后它就连接到数据库,运行SQL命令,在
DataGrid
中显示数据,最后退出函数。
BindGrid(db,SQL,DataGrid)
BindGrid(
"告诉我是什么数据库"
,
"告诉我你想运行什么SQL语句"
,
"告诉我你想在哪个DataGrid中显示数据"
)

BindGrid 输入

private void BindGrid(stringDBconnectString,
   stringsqlCommand,System.Web.UI.WebControls.DataGridDGrid)
string
DBconnectString
: Databasestring
sqlCommand
: SQL
System.Web.UI.WebControls.DataGridDGrid
:
DataGrid
注意:你在C#中可以为这个函数指定一个Web控件作为输入。所有你必须做的事情是指定哪一个
DataGrid
是你想要使用这个函数的。
private void BindGrid(stringDBconnectString,
      stringsqlCommand,System.Web.UI.WebControls.DataGridDGrid)
// 从数据库中加载初始化页面
  // 绑定到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();
}

调用 BindGrid()

函数
BindGrid()
的详细说明:数据库连接字符串:在 Web.Config 中指定SQL 字符串:任意SQL字符串,甚至可以是存储过程
DataGrid
DataGrid
的标识符
private void Page_Load(object sender,System.EventArgs e)
{
  // 构造SQL字符串
  string SQLstring = "Select * FROM Employee";
  // 调用并构造BindGrid
  BindGrid(strConnectSQL,SQLstring,DataGrid1 );
}

使用多个 DataGrids

通过不同的SQL命令,在页面上放置三个
DataGrid
。如下面所示,只要调用具有不同SQL命令的
BindGrid()
三次就可以了。所以现在你可以使用相同的代码使用多个
DataGrid
// DataGrid1
string SQLstring1 = "Select * FROM Employee";
BindGrid(strConnectSQL,SQLstring1,DataGrid1 );
// DateGrid 2
string SQLstring2 = "Select * FROM Customers";
BindGrid(strConnectSQL,SQLstring2,DataGrid2 );
//DataGrid3
string SQLstring3 = "Select * FROM Orsders";
BindGrid(strConnectSQL,SQLstring3,DataGrid3 );

使用 BindList()

好了。现在我们将从使用
BindGrid()
转向使用
BindList()
,它可以使用ASP.NET中的下拉列表。代码稍微有点难理解了,因为
DropDownList
多了两个属性:
DataTextField
: 下拉列表中所显示的,也就是用户所看到的。
DataValueField
: 测定用户的选择的值。这些值都被添加到
BindList()
的输入参数中,所以可以像这样运行它:
BindList(db,SQL,Text,Value,DropDownList);
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 BindList
{
  public class WebForm1 : System.Web.UI.Page
  {
    protected System.Web.UI.WebControls.DropDownList DropDownList1;
    // 从 web.config 获得连接字符串
    public String strConnectSQL =
        (ConfigurationSettings.AppSettings["dsn_SQL"]);
    private void Page_Load(object sender,System.EventArgs e)
    {
      // 创建SQL字符串
      string SQLstring = "Select EmployeeID,FirstName + ' ' + LastName" +
                         " as name FROM Employees";
      string TextField = "name";
      string ValueField = "EmployeeID";
      BindList(strConnectSQL,SQLstring,TextField ,
                              ValueField,DropDownList1 );
    }
    private void BindList(string strConnectSQL,string SQLstring,
            string TextField,string ValueField,
            System.Web.UI.WebControls.DropDownList Dlist)
    {
      SqlConnection myConnection = new SqlConnection(strConnectSQL);
      SqlCommand myCommand = new SqlCommand( SQLstring,myConnection );
      myConnection.Open();
      Dlist.DataSource = myCommand.ExecuteReader();
      Dlist.DataTextField = TextField;
      Dlist.DataValueField = ValueField;
      Dlist.DataBind();
      myConnection.Close();
    }
#region Web Form Designer generated code
    override protected void OnInit(EventArgs e)
    {
      //
      // CODEGEN: This call is required by the ASP.NET Web Form Designer.
      //
      InitializeComponent();
      base.OnInit(e);
    }
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
    private void InitializeComponent()
    {
      this.Load += new System.EventHandler(this.Page_Load);
    }
#endregion
  }
}

有趣的地方

这样做的好处之一就是你可以在ASP.NET中指定 web 控件作为函数的输入参数。这确实改变了我的编码习惯,我现在正在开发更多的一般性的可重用代码。

为什么使用这些代码

这非常简单。一旦你要为一个特定的控件编码,你就不必再重新写一次了。你可以一次又一次地使用相同的代码。

历史

2004年11月 V1.1
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: