课程名称 .NET程序设计 实验名称 实验七 ADO.NET管理数据库
一.实验目的:
1.掌握ASP.NET服务器验证控件的使用。
2.掌握ADO.NET对象的使用方法。
3.初步熟悉数据绑定控件GridView控件的使用方法。
二.实验内容:
本实验将通过创建一个的“C#学习网”,使同学们掌握ASP.NET服务器验证控件、ADO.NET对象的使用方法,并初步熟悉数据绑定控件GridView。该网站各页的效果图如图7-1、7-2、7-3、7-4、7-5、7-6、7-7、7-8所示。大体上的功能是:
(1)首次访问网站首页index.aspx页(图7-4)时,该页面判断是否“已登录”,若未登录,则自动跳转到login.aspx页(图7-1),若输入正确的用户名和密码,单击“登录”按钮,则跳转到index.aspx;若单击“注册”按钮,则跳转到Register.aspx(图7-2),若注册成功,就跳转到RegisterSuccess.aspx(图7-3)注册成功页面,单击该页上的“确定”按钮,就跳转到index.aspx页面。
(2)在index.aspx页面,单击“新闻管理”,跳转到news.aspx(图7-5)。在该页面单击“单击此处发布新闻”,跳转到发布新闻页面modifyNews.aspx(图7-6),输入完毕后,单击“确定”按钮,回到news.aspx页面;在该页面单击某条新闻记录的“编辑”按钮,跳转到修改页面modifyNews.aspx(图7-7),修改完毕后,单击“确定”按钮,回到news.aspx。
(3)在index.aspx页面,单击“新闻浏览”,跳转到allnews.aspx(图7-8)
在设计页面之前,首先根据效果图分析得到框架结构代码,并利用PhotoShop工具,剪切下需要的图片,并保存(本实验已提供了这些图片)。
图7-1 登录页面效果
图 7-2 注册页面效果
图7-3 登录成功页面效果
图7-4 网站首页效果
图7-5 新闻管理页面效果
图7-6 新闻发布页面效果
图 7-7 修改新闻页面效果
图7-8 新闻浏览页面效果
图7-9 新闻内容页面效果
1.创建数据库和数据库表
“C#学习网”中用到了两个表:userlogin表和news表。我们首先创建一个数据库,名为“C#StudyDB”,然后按照图7-10和7-11所示的表结构创建userlogin表和news表。
图7-10 userlogin表结构
图7-11 news表结构
2.创建登录页面
(1)启动Visual Studio 2008,新建一个名为学习网 动态网站的ASP.NET网站。并新建一个名为images的文件夹,通过添加现有项的方法将本实验提供的图片素材添加到网站的images文件中。(注:所有图片已放在本实验的附件中)
(2)在【解决资源管理器】窗格中右击选择【添加新项】命令或者选择【项目】|【添加新项】命令,打开【添加新项】对话框。选择“Web窗体“,并取名为“login.aspx”。按照图7-1所示的效果设计页面,将用于用户名输入的TextBox取名为“TextBoxUsername”,用于密码输入的TextBox取名为“TextBoxPassword”,“登录”按钮取名为“ButtonLogin”,“注册”按钮取名为“ButtonRegister”。
(3)编写“ButtonLogin”按钮的Click事件代码,如下:
protected void ButtonLogin_Click(object sender, EventArgs e)
{ string strName = TextBoxUsername.Text;
string strPwd = TextBoxPassword.Text;
string strConn ="Data Source=localhost;uid=sa;pwd=888888;DataBase=C#StudyDB";
SqlConnection conn = new SqlConnection(strConn);
string strSelect = "SELECT * FROM userlogin WHERE username =@username and userpwd =@password";
SqlCommand command = new SqlCommand(strSelect,conn);
command.Parameters.AddWithValue("@username",strName);
command.Parameters.AddWithValue("@password",strPwd);
conn.Open();
SqlDataReader dr = command.ExecuteReader();
if (dr.Read())
{
Session["userName"] = strName;
Server.Transfer("index.aspx");
}
else
{
Session["userName"] = "";
this.ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('登录失败,无此用户名或密码不正确!');</script>");
}
conn.Close();
}
(4)编写ButtonRegister按钮的Click事件代码如下:
protected void ButtonRegister_Click(object sender, EventArgs e)
{
Server.Transfer("register.aspx");
}
3.创建注册页面
(1)在【解决资源管理器】窗格中右击选择【添加新项】命令或者选择【项目】|【添加新项】命令,打开【添加新项】对话框。选择“Web窗体“,并取名为“Register.aspx”。按照图7-2所示的效果设计页面,将用于用户名输入的TextBox取名为“TextBoxName”,用于密码输入的TextBox取名为“TextBoxPwd”,用于确认密码的TextBox取名为“TextBoxRePwd”,用于输入性别的是一个RadioButtonList控件RadioButtonList1。
(2)使用必须字段验证控件确保TextBoxName、TextBoxPwd和TextBoxRePwd不能为空,使用正则表达式验证控件确保TextBoxName和TextBoxPwd为“3到10个字母、数字”,使用比较验证控件确保TextBoxPwd和TextBoxRePwd必须一致。其核心代码如下:
<table style="width:438px; line-height:30px; height: 214px; margin-left:10px;">
<tr>
<td class="style1">
用户名:</td>
<td class="style2">
<asp:TextBox ID="TextBoxName" runat="server" Width="125px"></asp:TextBox>
</td>
<td>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"
ControlToValidate="TextBoxName" Display="Dynamic" ErrorMessage="不能为空"></asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server"
ControlToValidate="TextBoxName" Display="Dynamic" ErrorMessage="要求3到16个数字、字母、_、-"
ValidationExpression="[a-zA-Z0-9_-]{3,16}"></asp:RegularExpressionValidator>
</td>
</tr>
<tr>
<td class="style1">
密码:</td>
<td class="style2">
<asp:TextBox ID="TextBoxPwd" runat="server" TextMode="Password" Width="125px"></asp:TextBox>
</td>
<td>
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server"
ControlToValidate="TextBoxPwd" Display="Dynamic" ErrorMessage="不能为空"></asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="RegularExpressionValidator2" runat="server"
ControlToValidate="TextBoxPwd" Display="Dynamic" ErrorMessage="要求3到10个字母、数字"
ValidationExpression="[0-9a-zA-Z]{3,10}"></asp:RegularExpressionValidator>
</td>
</tr>
<tr>
<td class="style1">
确认密码:</td>
<td class="style2">
<asp:TextBox ID="TextBoxRePwd" runat="server" TextMode="Password" Width="125px"></asp:TextBox>
</td>
<td>
<asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server"
ControlToValidate="TextBoxRePwd" Display="Dynamic" ErrorMessage="不能为空"></asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="RegularExpressionValidator3" runat="server"
ControlToValidate="TextBoxRePwd" Display="Dynamic" ErrorMessage="要求3到10个字母、数字"
ValidationExpression="[0-9a-zA-Z]{3,10}"></asp:RegularExpressionValidator>
<asp:CompareValidator ID="CompareValidator1" runat="server"
ControlToCompare="TextBoxPwd" ControlToValidate="TextBoxRePwd"
Display="Dynamic" ErrorMessage="两次输入的密码不同"></asp:CompareValidator>
</td>
</tr>
<tr>
<td class="style1">
性别:</td>
<td class="style2">
<asp:RadioButtonList ID="RadioButtonList1" runat="server" Height="25px"
RepeatDirection="Horizontal" Width="119px">
<asp:ListItem Selected="True">男</asp:ListItem>
<asp:ListItem>女</asp:ListItem>
</asp:RadioButtonList>
</td>
<td>
</td>
</tr>
<tr>
<td colspan="3" align="center">
(说明:以上各项必须全部填写)</td>
</tr>
<tr>
<td colspan="3" align="center">
<asp:Button ID="ButtonOk" runat="server" onclick="ButtonOk_Click"
Text="确定" Width="64px" />
</td>
</tr>
</table>
(3)编写“确定”按钮ButtonOk的Click事件代码如下:
protected void ButtonOk_Click(object sender, EventArgs e)
{
string strCheckUser = "SELECT * FROM userlogin WHERE username =@name";
string strInsertUser = "INSERT INTO userlogin (username, userpwd, sex, logintime) VALUES (@name,@password,@sex,'" + DateTime.Now + "')";
string strConn = "Data Source=localhost;uid=sa;pwd=888888;DataBase=C#StudyDB";
SqlConnection conn = new SqlConnection(strConn);
SqlCommand command = new SqlCommand(strCheckUser,conn);
command.Parameters.AddWithValue("@name",TextBoxName.Text.Trim());
command.Parameters.AddWithValue("@password",TextBoxPwd.Text.Trim());
command.Parameters.AddWithValue("@sex", RadioButtonList1.SelectedItem.Text);
conn.Open();
SqlDataReader dr = command.ExecuteReader();
if (dr.Read())
{ conn.Close();
this.ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('注册失败,已有该用户名!');</script>"); // ClientScript.RegisterStartupScript用来向前台页面注册script脚本, this.GetType()为注册脚本控件类型;""为脚本函数的名字,随便起。"<script>alert('注册失败,已有该用户名!');</script>"为脚本内容。
}
else
{ dr.Close();
command.CommandText=strInsertUser;
command.ExecuteNonQuery();
conn.Close();
Session["userName"] = TextBoxName.Text.Trim();
Server.Transfer("RegisterSuccess.aspx");
}
}
4.创建新闻管理页面
(1)在【解决资源管理器】窗格中右击选择【添加新项】命令或者选择【项目】|【添加新项】命令,打开【添加新项】对话框。选择“Web窗体“,并取名为“news.aspx”。按照图7-5所示的效果设计页面。在该页面中添加一个GridView控件,点击该该控件右端的“>”按钮,打开“GridView任务”对话框,选择“编辑列”选项,添加“标题”、“发布日期”、“发布者”以及“浏览次数”绑定列字段并做必要的设定,添加“编辑”链接列字段,添加“删除”命令列字段。再次打开“GridView任务”对话框,选择“自动套用格式”对话框中的“传统型”格式,以上步骤将自动产生以下GridView代码:
<asp:GridView ID="GridView1" runat="server" AllowSorting="True" AutoGenerateColumns="False"
CellPadding="4" DataKeyNames="id" ForeColor="#333333" GridLines="None"
Width="100%" Font-Size="12px" onrowdeleting="GridView1_RowDeleting" >
<FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<Columns>
<asp:BoundField DataField="标题" HeaderText="标题" SortExpression="标题" />
<asp:BoundField DataField="发布日期" HeaderText="发布日期" SortExpression="发布日期" DataFormatString="{0:yyyy-M-d h:m}" HtmlEncode="False" />
<asp:BoundField DataField="发布者" HeaderText="发布者" SortExpression="发布者" />
<asp:BoundField DataField="浏览次数" HeaderText="浏览次数" SortExpression="浏览次数" />
<asp:HyperLinkField DataNavigateUrlFields="id" DataNavigateUrlFormatString="modifyNews.aspx?mess=1&id={0}" Text="编辑" />
<asp:CommandField ShowDeleteButton="True" />
</Columns>
<RowStyle BackColor="#EFF3FB" />
<EditRowStyle BackColor="#2461BF" />
<SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
<PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
<HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<AlternatingRowStyle BackColor="White" />
</asp:GridView>
(2)在后台代码中,首先添加一个私有方法DataBinding()用于绑定数据,其代码如下:
private void DataBinding()
{ string ConnStr = "server=localhost;database=C#StudyDB;uid=sa;pwd=888888";
SqlConnection conn = new SqlConnection(ConnStr);
SqlCommand cmd = new SqlCommand();
SqlDataAdapter sda = new SqlDataAdapter();
DataSet ds = new DataSet();
conn.Open();
cmd.Connection = conn;
cmd.CommandText = "select * from news where 发布者=@Name";
sda.SelectCommand = cmd;
cmd.Parameters.AddWithValue("@Name", Session["userName"].ToString());
sda.Fill(ds);
GridView1.DataSource = ds.Tables[0];
GridView1.DataBind();
conn.Close();
}
(3)编写页面的Page_Load事件代码和GridView1的RowDeleting事件代码如下:
protected void Page_Load(object sender, EventArgs e)
{
DataBinding();
}
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
SqlConnection conn = new SqlConnection("Data Source=localhost;uid=sa;pwd=888888;DataBase=C#StudyDB");
conn.Open();
SqlCommand command = new SqlCommand("delete news where id=@id", conn); command.Parameters.AddWithValue("@id",GridView1.DataKeys[e.RowIndex].Value.ToString());
command.ExecuteNonQuery();
conn.Close();
DataBinding();
}
5.创建发布/修改新闻页面
发布新闻和修改新闻页面都是同一个页面modifyNews.aspx。根据查询字符串参数mess的不同取值来区分不同的功能。当链接“发布新闻”功能时,mess=0;当链接“修改新闻”功能时,mess=1。下面给出具体创建过程。
(1)在【解决资源管理器】窗格中右击选择【添加新项】命令或者选择【项目】|【添加新项】命令,打开【添加新项】对话框。选择“Web窗体“,并取名为“modifyNews.aspx”。按照图7-6所示的效果设计页面。在该页面中前后添加两个TextBox: TextBox1和TextBox2,分别用输入新闻标题和新闻内容。还有两个Button: ButtonOK和ButtonCancel,分别用于“确定”和“取消”输入。
(2)参数mess的值是在TextBox的Init事件中读取的(因为Page_Load事件在按钮控件被点击时自动执行,所以读取参数mess的任务不能由Page_Load事件代码完成),下面为TextBox添加Init事件代码如下:
protected void TextBox_Init(object sender, EventArgs e)
{
TextBoxInit();
}
protected void TextBoxInit()
{
message = Request.QueryString["mess"];
Session["id"] = Request.QueryString["id"];
switch (message)
{
case "0": //发布新闻
{
Label1.Text = "发布新闻";
break;
}
case "1": //修改新闻
{
Label1.Text = "修改新闻";
SqlConnection conn = new SqlConnection("Data Source=localhost;uid=sa;pwd=888888;DataBase=C#StudyDB");
SqlCommand command = new SqlCommand("select * from news where id=@id", conn);
command.Parameters.AddWithValue("@id", Session["id"].ToString());
conn.Open();
SqlDataReader rd = command.ExecuteReader();
if (rd.Read())
{
TextBox1.Text = rd["标题"].ToString();
TextBox2.Text = " "+rd["内容"].ToString();
rd.Close();
}
else
{
this.ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('无此记录!');</script>");
}
conn.Close();
break;
}
}
}
(3)编写两个按钮的事件代码及相关方法如下:
protected void ButtonOK_Click(object sender, System.EventArgs e)
{
if (message == "0") //发布新闻
{
if (FindZhuTi() == true)
{
this.ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('库中已经有要发布的标题,无法重复发布!');</script>");
return;
}
else
{
SqlConnection conn = new SqlConnection("Data Source=localhost;uid=sa;pwd=888888;DataBase=C#StudyDB");
conn.Open();
SqlCommand command = new SqlCommand("insert into news(标题,内容,发布日期,发布者,浏览次数) values(@title,@content,@date,@username,0)", conn);
command.CommandType = CommandType.Text;
command.Parameters.AddWithValue("@title", this.TextBox1.Text.Trim());
command.Parameters.AddWithValue("@content", this.TextBox2.Text.Trim());
command.Parameters.AddWithValue("@date", DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss"));
command.Parameters.AddWithValue("@username", Session["userName"].ToString());
command.ExecuteNonQuery();
conn.Close();
Server.Transfer("news.aspx");
}
}
else if (message == "1") //修改新闻
{
SqlConnection conn = new SqlConnection("Data Source=localhost;uid=sa;pwd=888888;DataBase=C#StudyDB");
conn.Open();
SqlCommand command = new SqlCommand("update news set 标题=@title,内容=@content,发布日期=@date where id=@id", conn);
command.CommandType = CommandType.Text;
command.Parameters.AddWithValue("@title", this.TextBox1.Text.Trim());
command.Parameters.AddWithValue("@content", this.TextBox2.Text.Trim());
command.Parameters.AddWithValue("@date", DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss"));
command.Parameters.AddWithValue("@id", Session["id"].ToString());
command.ExecuteNonQuery();
conn.Close();
Server.Transfer("news.aspx");
}
}
private bool FindZhuTi()
{
bool isFind = false;
SqlConnection conn = new SqlConnection("Data Source=localhost;uid=sa;pwd=888888;DataBase=C#StudyDB");
SqlCommand command = new SqlCommand("select 标题 from news order by 标题", conn);
SqlDataReader rd = null;
conn.Open();
rd = command.ExecuteReader();
while (rd.Read())
{
if (rd["标题"].ToString().Trim() == this.TextBox1.Text.Trim())
{
isFind = true;
break;
}
}
rd.Close();
conn.Close();
return isFind;
}
protected void ButtonCancel_Click(object sender, System.EventArgs e)
{
Server.Transfer("news.aspx");
}
6.其他页面的创建
以上给出了“C#学习网”的主要页面的大致创建过程。其他页面根据要求创建。
三、实验代码
四、实验结果
1.首页
2.新闻管理
3.发布新闻
4.新闻浏览
5.登录
6.注册
7.注册成功
8.数据库
9.用户注册成功数据库
五、实验总结
掌握各页面的逻辑关系转跳,掌握ASP.NET服务器验证控件的使用。掌握ADO.NET对象的使用方法。初步熟悉数据绑定控件GridView控件的使用方法。掌握SqlServer数据库的使用方法。
代码资源下载链接:https://download.csdn.net/download/XIARIANNUAN/13137650