asp.net 初级入门学习之ATM

本文介绍了作者使用ASP.NET基础进行ATM模拟应用的开发过程,旨在巩固学习成果。开发环境为VS2013,操作系统为Windows 8.1,数据库采用Access 2010。虽然界面简洁,但实现了ATM基本功能,未限制交易金额为100的整数倍。文章提供了login.aspx.cs的代码片段和AccessHelper类的源码,供读者进一步学习和实践。
摘要由CSDN通过智能技术生成

 这不, 看到这个14:00, 就想起昨晚整到凌晨才把这个ATM写完, 提笔的有点晚,不过, 基本上还是完成了。


本次博文的目的是把刚学的asp.net基础知识再巩固下。若有雷同,纯属偶合~~~大笑


开发环境:VS2013, 开发平台:windows8.1, 使用数据库版本:Access 2010


ATM的效果图:

  


    


 


 

界面做的简单了点儿, 但是基本上是实现了ATM的基本功能的

但是笔者  指出一点: 笔者并没有做的像ATM那样,每次取钱或这存钱均为100的整数倍, 当时在做的时候, 想到,不过是加上限制条件,不过笔者有点困,就没做啦~~~~吐舌头



login.aspx.cs  登陆界面的代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.OleDb;

namespace HR
{
    public partial class login : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void loginBtn_Click(object sender, EventArgs e)
        {
            string selectStr = "select * from login where 账户 = '"+AccountBox.Text+"' and 密码 = '"+KeyBox.Text+"'";
            DataSet ds = AccessHelper.dataSet(selectStr);
            if (ds.Tables[0].Rows.Count > 0)
            {
                ///---session 保存登录信息
                Session["userName"] = AccountBox.Text;
                Session["key"] = KeyBox.Text;
                Response.Redirect("index.aspx");
            }
            else
            {
                Response.Write("<script>alert('用户名或者密码错误')</script>");
                AccountBox.Text = "";
                KeyBox.Text = "";
            }
        }
    }
}

index.aspx.cs 主界面代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.OleDb;
using System.Data;

namespace HR
{
    public partial class index : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            ///---先判断是否登录账户
            if (Session["userName"] != null && Session["key"] != null)
            {           
                Account_CountLabel.Visible = false;
            }
            else
            {
                ///--跳转到 登录界面
                Response.Redirect("login.aspx");
            }
        }

        /// <summary>
        /// ---注销, 直接返回到登录界面, 清空: session 内的 内容
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void logOffBtn_Click(object sender, EventArgs e)
        {
            Session["userName"] = "";
            Session["key"] = "";
            Response.Redirect("login.aspx");
        }


        /// <summary>
        /// ---_取钱按钮消息事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void GetBtn_Click(object sender, EventArgs e)
        {
            Response.Redirect("GetMoney.aspx"); 
        }


        /// <summary>
        /// ----显示余额按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Account_CountBtn_Click(object sender, EventArgs e)
        {
            DataSet ds = AccessHelper.dataSet("select * from Account");
            Account_Label.Text += ds.Tables[0].Rows[0][0].ToString();
            AccountName_Label.Text += ds.Tables[0].Rows[0][1].ToString();
            Account_CountLabel.Text += ds.Tables[0].Rows[0][2].ToString();
            Account_CountLabel.Visible = true;

            ///--禁用按钮 : 显示余额
            Account_CountBtn.Enabled = false;
        }


        /// <summary>
        /// --存钱按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void saveBtn_Click(object sender, EventArgs e)
        {
            Response.Redirect("saveMoney.aspx");
        }
    }
}

取钱页面:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.OleDb;
using System.Data;

namespace HR
{
    public partial class GetMoney : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Session["userName"] != null && Session["key"] != null)
            {
                DataSet ds = AccessHelper.dataSet("select * from Account");
            ///--显示余额
            Label1.Text += ds.Tables[0].Rows[0][2];
            }
            else
            {
                ///--跳转到 登录界面
                Response.Redirect("login.aspx");
            }
        }

        protected void sureBtn_Click(object sender, EventArgs e)
        {
            if (money_NumBox.Text == "")
            {
                Response.Write("<script>alert('取款数不能为空')</script>");
            }
            else
            {
                //获取输入的取钱数目,
                float tempF = float.Parse(money_NumBox.Text);

                DataSet ds = AccessHelper.dataSet("select * from Account");
                float allStr = float.Parse(ds.Tables[0].Rows[0][2].ToString()); // 所有额
                ///---取钱数<= 余额
                if (tempF < allStr && tempF > 0)
                {
                    ///---计算余额
                    float restStr = allStr - tempF;

                    ///----更新数据库操作
                    string upDateStr = "update Account set 账户 = '" + Session["userName"] + "' , 户主 = '" + ds.Tables[0].Rows[0][1].ToString() + "' , 余额 = '" + restStr.ToString() + "' ";
                    AccessHelper.excuteSql(upDateStr);

                    ///---提示:取走现金
                    Response.Write("<script>alert('请取走您的现金, 注意财产安全')</script>");

                    DataSet ds1 = AccessHelper.dataSet("select * from Account");
                    Label1.Text = "您的余额:" + ds1.Tables[0].Rows[0][2].ToString();

                    ///---清空输入框内的数据
                    money_NumBox.Text = "";
                }
                else
                {
                    ///--取款失败
                    Response.Write("<script>alert('取款失败,输入的数据非法')</script>");

                    ///---清空输入框
                    money_NumBox.Text = "";
                }
            }
        }


        /// <summary>
        /// -返回到主页
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void BackBtn_Click(object sender, EventArgs e)
        {
            Response.Redirect("index.aspx");
        }
    }
}

存款界面的代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.OleDb;

namespace HR
{
    public partial class saveMoney : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
             if (Session["userName"] != null && Session["key"] != null)
             {
                 ///--加载余额
                 DataSet ds = AccessHelper.dataSet("select * from Account");
                 Label1.Text += ds.Tables[0].Rows[0][2].ToString();
             }
             else
             {
                 ///--跳转到 登录界面
                 Response.Redirect("login.aspx");
             }
           
        }


        /// <summary>
        /// ---返回到主页
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void BackBtn_Click(object sender, EventArgs e)
        {
            Response.Redirect("index.aspx");
        }


        /// <summary>
        /// ---确定存钱按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void saveBtn_Click(object sender, EventArgs e)
        {
            if (saveMoneyBox.Text == "" || float.Parse(saveMoneyBox.Text) < 0)
            {
                ///---提示存钱失败
                Response.Write("<script>alert('存钱失败,存钱数不正确')</script>");
            }
            else
            {
                ///---输入的存款数为正数
                //获取输入的取钱数目,
                float tempF = float.Parse(saveMoneyBox.Text);

                DataSet ds = AccessHelper.dataSet("select * from Account");
                float allStr = float.Parse(ds.Tables[0].Rows[0][2].ToString()); // 所有额
                ///---取钱数<= 余额
                if (tempF > 0)
                {
                    ///---计算余额
                    float restStr = allStr + tempF;

                    ///----更新数据库操作
                    string upDateStr = "update Account set 账户 = '" + Session["userName"] + "' , 户主 = '" + ds.Tables[0].Rows[0][1].ToString() + "' , 余额 = '" + restStr.ToString() + "' ";
                    AccessHelper.excuteSql(upDateStr);

                    ///---提示:取走现金
                    Response.Write("<script>alert('存款成功')</script>");

                   ///---更新金额提示label
                    DataSet ds1 = AccessHelper.dataSet("select * from Account");
                    Label1.Text = "您的余额:" + ds1.Tables[0].Rows[0][2].ToString();

                    ///---清空输入框内的数据
                    saveMoneyBox.Text = "";
                }
                else
                {
                    ///--取款失败
                    Response.Write("<script>alert('取款失败,输入的数据非法')</script>");

                    ///---清空输入框
                    saveMoneyBox.Text = "";
                }
            }
        }
    }
}

提示:

笔者代码里面使用一个名为AccessHelper的类, 这里面封装了数据库的一些常用操作。稍加修改, 这个类可以适用于SQL。之前的博文也说到过这个AccessHelper类,

这里,我把这个类的代码还是贴出来。

============================ AccessHelper 类 源码======================================

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.OleDb;
using System.Web;


    public class AccessHelper
    {
        protected static OleDbConnection conn = new OleDbConnection();
        protected static OleDbCommand comm = new OleDbCommand();

        public AccessHelper()
        {
            //
            // TODO: 在此处添加构造函数逻辑
            //
        }
         
        /// <summary>
        /// 打开数据库
        /// </summary>
        private static void openConnection()
        {
            if (conn.State == ConnectionState.Closed)
            {
                conn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source= " + HttpContext.Current.Server.MapPath("1.accdb") + " ";
                comm.Connection = conn;
                try
                {
                    conn.Open();
                }
                catch (Exception e)
                { throw new Exception(e.Message); }

            }

        }
        /// <summary>
        /// 关闭数据库
        /// </summary>
        private static void closeConnection()
        {
            if (conn.State == ConnectionState.Open)
            {
                conn.Close();
                conn.Dispose();
                comm.Dispose();
            }
        }
        /// <summary>
        /// 执行sql语句
        /// </summary>
        /// <param name="sqlstr"></param>
        public static void excuteSql(string sqlstr)
        {
            try
            {
                openConnection();
                comm.CommandType = CommandType.Text;
                comm.CommandText = sqlstr;
                comm.ExecuteNonQuery();
            }
            catch (Exception e)
            {
                throw new Exception(e.Message);
            }
            finally
            { closeConnection(); }
        }
        /// <summary>
        /// 返回指定sql语句的OleDbDataReader对象,使用时请注意关闭这个对象。
        /// </summary>
        /// <param name="sqlstr"></param>
        /// <returns></returns>
        public static OleDbDataReader dataReader(string sqlstr)
        {
            OleDbDataReader dr = null;
            try
            {
                openConnection();
                comm.CommandText = sqlstr;
                comm.CommandType = CommandType.Text;

                dr = comm.ExecuteReader(CommandBehavior.CloseConnection);
            }
            catch
            {
                try
                {
                    dr.Close();
                    closeConnection();
                }
                catch { }
            }
            return dr;
        }
        /// <summary>
        /// 返回指定sql语句的OleDbDataReader对象,使用时请注意关闭
        /// </summary>
        /// <param name="sqlstr"></param>
        /// <param name="dr"></param>
        public static void dataReader(string sqlstr, ref OleDbDataReader dr)
        {
            try
            {
                openConnection();
                comm.CommandText = sqlstr;
                comm.CommandType = CommandType.Text;
                dr = comm.ExecuteReader(CommandBehavior.CloseConnection);
            }
            catch
            {
                try
                {
                    if (dr != null && !dr.IsClosed)
                        dr.Close();
                }
                catch
                {
                }
                finally
                {
                    closeConnection();
                }
            }
        }
        /// <summary>
        /// 返回指定sql语句的dataset
        /// </summary>
        /// <param name="sqlstr"></param>
        /// <returns></returns>
        public static DataSet dataSet(string sqlstr)
        {
            DataSet ds = new DataSet();
            OleDbDataAdapter da = new OleDbDataAdapter();
            try
            {
                openConnection();
                comm.CommandType = CommandType.Text;
                comm.CommandText = sqlstr;
                da.SelectCommand = comm;
                da.Fill(ds);

            }
            catch (Exception e)
            {
                throw new Exception(e.Message);
            }
            finally
            {
                closeConnection();
            }
            return ds;
        }
        /// <summary>
        /// 返回指定sql语句的dataset
        /// </summary>
        /// <param name="sqlstr"></param>
        /// <param name="ds"></param>
        public static void dataSet(string sqlstr, ref DataSet ds)
        {
            OleDbDataAdapter da = new OleDbDataAdapter();
            try
            {
                openConnection();
                comm.CommandType = CommandType.Text;
                comm.CommandText = sqlstr;
                da.SelectCommand = comm;
                da.Fill(ds);
            }
            catch (Exception e)
            {
                throw new Exception(e.Message);
            }
            finally
            {
                closeConnection();
            }
        }
        /// <summary>
        /// 返回指定sql语句的datatable
        /// </summary>
        /// <param name="sqlstr"></param>
        /// <returns></returns>
        public static DataTable dataTable(string sqlstr)
        {
            DataTable dt = new DataTable();
            OleDbDataAdapter da = new OleDbDataAdapter();
            try
            {
                openConnection();
                comm.CommandType = CommandType.Text;
                comm.CommandText = sqlstr;
                da.SelectCommand = comm;
                da.Fill(dt);
            }
            catch (Exception e)
            {
                throw new Exception(e.Message);
            }
            finally
            {
                closeConnection();
            }
            return dt;
        }
        /// <summary>
        /// 返回指定sql语句的datatable
        /// </summary>
        /// <param name="sqlstr"></param>
        /// <param name="dt"></param>
        public static void dataTable(string sqlstr, ref DataTable dt)
        {
            OleDbDataAdapter da = new OleDbDataAdapter();
            try
            {
                openConnection();
                comm.CommandType = CommandType.Text;
                comm.CommandText = sqlstr;
                da.SelectCommand = comm;
                da.Fill(dt);
            }
            catch (Exception e)
            {
                throw new Exception(e.Message);
            }
            finally
            {
                closeConnection();
            }
        }
        /// <summary>
        /// 返回指定sql语句的dataview
        /// </summary>
        /// <param name="sqlstr"></param>
        /// <returns></returns>
        public static DataView dataView(string sqlstr)
        {
            OleDbDataAdapter da = new OleDbDataAdapter();
            DataView dv = new DataView();
            DataSet ds = new DataSet();
            try
            {
                openConnection();
                comm.CommandType = CommandType.Text;
                comm.CommandText = sqlstr;
                da.SelectCommand = comm;
                da.Fill(ds);
                dv = ds.Tables[0].DefaultView;
            }
            catch (Exception e)
            {
                throw new Exception(e.Message);
            }
            finally
            {
                closeConnection();
            }
            return dv;
        }
    }

=====================AccessHelper 类代码  至此 ======================

这不,代码都贴出来了,相信,消化它,剩下的就是时间问题啦~~~~~~



这里 是本次练手源码下载地址~~~~~~~微笑微笑微笑微笑微笑


这是ASP.NET的文档using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ATM { class Bank { private List<Account> accounts; public List<Account> Accounts { get { return accounts; } set { accounts = value; } } private int currentAccountNumber; public int CurrentAccountNumber { get { return currentAccountNumber; } set { currentAccountNumber = value; } } public Bank() { accounts = new List<Account>(); } public Account OpenAccount(string password, string confirmationPassword, string name, string personId, string email, int typeOfAccount) { Account newAccount; if (!password.Equals(confirmationPassword)) { throw new InvalidOperationException("两次密码输入的不一致!"); } switch (typeOfAccount) { case 1: newAccount = new SavingAccount(password, name, personId, email); break; case 2: newAccount = new CreditAccount(password, name, personId, email); break; default:throw new ArgumentOutOfRangeException("账户类型是1到2之间的整数"); } accounts.Add(newAccount); return newAccount; } private Account GetAccountByID(long id) { foreach (Account account in accounts) { if(account.ID==id) { return account; } } return null; } public Account SignIn(long id, string password) { foreach (Account account in accounts) { if (account.ID == id && account.Password.Equals(password)) { return account; } } throw new InvalidOperationException("用户名或者密码不正确,请重试!"); } public Account Deposit(long id, double sum) { Account account = GetAccountByID(id); if (account != null) { account.Deposit(sum); return account; } throw new InvalidOperationException("非法账号!"); } public Account Withdraw(long id, double sum) { Account account = GetAccountByID(id); if (account != null) { account.Withdraw(sum); return account; } throw new InvalidOperationException("非法账号!"); } public Account SetCeiling(long id, double newCeiling) { Account account = GetAccountByID(id); try { (account as CreditAccount).Ceiling = newCeiling; return account; } catch (Exception ex) { throw new InvalidOperationException("此账户不是信用账户!"); } throw new InvalidOperationException("非法账号!"); } public double GetTotalBalance() { double totalBalance = 0; foreach (Account account in accounts) { totalBalance += account.Balance; } return totalBalance; } public double GetTotalCeiling() { double totalCeiling = 0; foreach (Account account in accounts) { if (account is CreditAccount) { totalCeiling += (account as CreditAccount).Ceiling; } } return totalCeiling; } } }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值