轻松在 DataGrids、下拉列表中使用 ADO






3.13/5 (23投票s)
2004年11月12日
3分钟阅读

93304

1181
一篇关于使用可重用代码轻松将 ADO 数据绑定到控件的文章。
引言
ADO 是从数据库中获取数据的一种非常强大的方式,但它也非常令人困惑,并且有许多技术和连接方法可以将您的数据放到 DataGrid
或其他控件上。我采取的方法是标准化并开发可重用的模块化代码来访问数据库和显示数据。我已经编写了 ASP.NET 页面,这些页面可以访问无限的 SQL 查询来在无限的 DataGrid
中显示结果。
本文将介绍我如何使用可重用代码连接 ADO 数据并在 DataGrid
和其他控件中显示结果数据。我还将介绍如何开发自己的代码来完成类似的任务。
背景
本文假设您了解 C#、SQL、ADO 和 .NET 控件的知识。
我在演示代码中使用了 NorthWind 数据库,但可以将其修改为使用任何数据库。
使用代码
Web.Config
我在 web.config 中使用 <appSettings>
来存储应用程序中使用的字符串。如果您从未在 web.config 中使用过应用程序设置,那么请务必尝试一下;我通常使用 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;
// Get the SQL Connection string from the web.config.
public String strConnectSQL =
(ConfigurationSettings.AppSettings["dsn_SQL"]);
private void Page_Load(object sender, System.EventArgs e)
{
// Build SQL String
string SQLstring = "Select * FROM Employee";
// Call and Build Grid
// BindGrid(SQLDBcontectString, SQLstring, DataGrid);
BindGrid(strConnectSQL, SQLstring, DataGrid1 );
}
private void BindGrid(string DBconnectString, string sqlCommand,
System.Web.UI.WebControls.DataGrid DGrid)
// Load intial page from database
// binds to datagrid
{
// create data connection
SqlConnection conn = new SqlConnection(DBconnectString);
// Call SQL from db
SqlCommand command = new SqlCommand(sqlCommand, conn);
// create data adapter
SqlDataAdapter adapter = new SqlDataAdapter(command);
// create and fill dataset
DataSet ds = new DataSet();
adapter.Fill(ds);
// fill and bind data to Datagrid
DGrid.DataSource = ds;
DGrid.DataBind();
// Close Connection
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;
// Get the SQL Connection string from the web.config.
public String strConnectSQL = (ConfigurationSettings.AppSettings["dsn_SQL"]);
private void BindGrid()
这是项目的核心部分。我将此代码放入任何我想从我的数据库中获取数据并将其显示到我的 DataGrid
的页面中。我无需编写复杂的 C# 或 ADO 代码。只需放入它,传递 DB、SQL、DataGrid
参数,它就会为我获取数据。
BindGrid() 的工作原理
您向 BindGrid()
传递数据库连接、SQL 字符串和 DataGrid
ID,它就会连接到您的数据库,运行 SQL 命令,并将数据显示在 DataGrid
中。
BindGrid( db, SQL, DataGrid)
BindGrid( "告诉我数据库", "告诉我你想运行的 SQL", "告诉我你想在哪个 DataGrid 中显示数据")
BindGrid 输入参数
private void BindGrid(string DBconnectString,
string sqlCommand, System.Web.UI.WebControls.DataGrid DGrid)
string DBconnectString
:数据库连接字符串string sqlCommand
:SQL 语句System.Web.UI.WebControls.DataGrid DGrid
:DataGrid
控件
注意: 您可以将 Web 控件指定为 C# 函数的输入参数。您所要做的就是指定函数要操作的 DataGrid
ID。
private void BindGrid(string DBconnectString,
string sqlCommand, System.Web.UI.WebControls.DataGrid DGrid)
// Load intial page from database
// binds to datagrid
{
// create data connection
SqlConnection conn = new SqlConnection(DBconnectString);
// Call SQL from db
SqlCommand command = new SqlCommand(sqlCommand, conn);
// create data adapter
SqlDataAdapter adapter = new SqlDataAdapter(command);
// create and fill dataset
DataSet ds = new DataSet();
adapter.Fill(ds);
// fill and bind data to Datagrid
DGrid.DataSource = ds;
DGrid.DataBind();
// Close Connection
conn.Close();
}
调用 BindGrid()
函数 BindGrid()
定义了
- 数据库连接字符串:如 Web.Config 中所述
- SQL 字符串:任何 SQL 字符串,甚至可以指定存储过程。
DataGrid
:DataGrid
的 ID。
private void Page_Load(object sender, System.EventArgs e)
{
// Build SQL String
string SQLstring = "Select * FROM Employee";
// Call and Build Grid
// BindGrid(SQLDBcontectString, SQLstring, DataGrid);
BindGrid(strConnectSQL, SQLstring, DataGrid1 );
}
填充多个 DataGrids
假设您想填充由不同 SQL 命令提供的三个 DataGrid
。只需像下面这样用不同的 SQL 命令调用 BindGrid()
三次。因此,您现在正在使用相同的代码来填充多个 DataGrid
。
// DataGrid 1
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
。
代码稍微复杂一些,因为 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;
// Get the SQL Connection string from the web.config.
public String strConnectSQL =
(ConfigurationSettings.AppSettings["dsn_SQL"]);
private void Page_Load(object sender, System.EventArgs e)
{
// Build SQL String
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
}
}
关注点
我在做这个的过程中学到的最好的事情之一是,您可以将 Web 控件指定为 ASP.NET 函数的输入参数。这确实改变了我的编码习惯,我现在正在开发更多通用的可重用代码。
为什么要使用这段代码
它非常简单。一旦为特定的控件编写好,您就再也不需要重写它了。您可以一遍又一遍地使用相同的代码。
历史
V1.1 2004 年 11 月