栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > .Net

.NET程序设计 实验七 ADO.NET管理数据库

.Net 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

.NET程序设计 实验七  ADO.NET管理数据库

课程名称 .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(), "", "");
        }
        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必须一致。其核心代码如下:

用户名:
密码:
确认密码:
性别: 男 女  
(说明:以上各项必须全部填写)

(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(), "", "");  // ClientScript.RegisterStartupScript用来向前台页面注册script脚本, this.GetType()为注册脚本控件类型;""为脚本函数的名字,随便起。""为脚本内容。
        }
        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代码:


            
                         
                   
                
                
                
                                
                                
            
            
            
            
            
            
            
        

(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(), "", "");
                     }
                    conn.Close();
                    break;
                }            
         }
    }

(3)编写两个按钮的事件代码及相关方法如下:

protected void ButtonOK_Click(object sender, System.EventArgs e)
    {
        if (message == "0")   //发布新闻
        {
            if (FindZhuTi() == true)
            {
                this.ClientScript.RegisterStartupScript(this.GetType(), "", "");
                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

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/909410.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号