Web
应用程序实践:
数据库应用开发
一、
创建
Web
项目和
Web
窗体
1、
创建
Web
项目——
Northwind
2、
创建两个
Web
窗体——
View.aspx
和
New.aspx
3、
设置
Web
应用程序时的起始页为
View.aspx
4、
添加一个类——
DataBase
5、
在
Web
窗体中添加控件并设置控件的属性
Web
窗体名称
|
文档标题
|
控件类别
|
控件
ID
|
备
注
|
View.aspx
|
显示数据
|
DataGrid
|
DataGrid1
|
显示数据
|
超链接
|
Html控件
|
链接到New.aspx
| ||
New.aspx
|
添加数据
|
TextBox
|
txtLname
|
输入
|
txtFname
|
| |||
txtAddr
|
| |||
txtPhone
|
| |||
Label
|
(4个)
|
标题
| ||
lblCue
|
提示
| |||
Button
|
btnSave
|
保存
| ||
btnCancel
|
取消
|
表
1-1 Web
窗体的控件
6、
添加
Web
应用程序代码
1)连接数据库,在Web.Config的
<
configuration
>下添加以下代码:
<appSettings>
<addkey="ConnectionString"value="Data Source=(local);uid=sa;pwd=sa; DataBase=Northwind;"/>
</appSettings>
|
在DataBase.cs添加以下代码:
//
引入以下命名空间
using
System.Data;
using
System.Data.SqlClient;
using
System.Configuration;
|
///<summary>
///
获取数据库连接集对象
///</summary>
public SqlConnection dbConn
{
get
{
string DSN;
SqlConnection _dbConn;
DSN = ConfigurationSettings.AppSettings["ConnectionString"];
_dbConn = new SqlConnection();
_dbConn.ConnectionString = DSN;
return _dbConn;
}
}
///<summary>
///
得到DataTable数据集
///</summary>
///<param name="sqlString">
用于查询的SQL文本
</param>
///<returns></returns>
public DataTable GetDataTable(string sqlString)
{
SqlCommand Command = new SqlCommand(sqlString, dbConn);
SqlDataAdapter Adapter = new SqlDataAdapter(Command);
DataTable dt = new DataTable();
Command.Connection.Open();
Adapter.SelectCommand = Command;
Adapter.Fill(dt);
Command.Connection.Close();
Command.Dispose();
Adapter.Dispose();
return dt;
}
|
2)
显示数据,在
View.aspx.cs
的
Page_Load
事件添加以下代码:
//
声明自定义类
DataBase mydb = new DataBase();
string sqlString;
sqlString = "SELECT LastName,FirstName,Address,HomePhone FROM Employees";
//
设置DataGrid的数据源
this.DataGrid1.DataSource = mydb.GetDataTable(sqlString);
//
绑定控件到指定的数据源
this.DataGrid1.DataBind();
|
3)
添加数据,在
New.aspx.cs
的
btnSave_Click
事件添加以下代码:
//
引入SqlClient命名空间
using System.Data.SqlClient;
|
//
必须输入FirstName
if (this.txtFname.Text == "")
{
this.lblCue.Text="Missing required field:FirstName";
return;
}
//
必须输入LastName
if (this.txtLname.Text == "")
{
this.lblCue.Text="Missing required field:LastName";
return;
}
DataBase mydb = new DataBase();
string sqlString = "SELECT * FROM Employees";
SqlCommand Command = new SqlCommand(sqlString, mydb.dbConn);
SqlDataAdapter Adapter = new SqlDataAdapter(Command);
SqlCommandBuilder Builder = new SqlCommandBuilder(Adapter);
DataTable dt = new DataTable();
DataRow dr;
Command.Connection.Open();
Adapter.SelectCommand = Command;
Adapter.Fill(dt);
//
创建新数据行
dr = dt.NewRow();
dr["LastName"] = this.txtLname.Text;
dr["FirstName"] = this.txtFname.Text;
dr["Address"] = this.txtAddr.Text;
dr["HomePhone"] = this.txtPhone.Text;
dt.Rows.Add(dr);
//
更新数据集
Adapter.Update(dt);
//
Response.Redirect("View.aspx");
|
7、
执行
Web
应用程序
1)单击“调试”菜单项;
2)点击“开始执行(不调试)”;
3)修改带波浪线的程序错误,然后重复以上步骤。
8、
测试
Web
应用程序
1)显示数据
2)添加数据
9、
课后练习——通过Web窗体实现编辑和删除数据。