您好,登录后才能下订单哦!
这篇“C#如何实现简单的点餐系统”除了程序员外大部分人都不太理解,今天小编为了让大家更加理解“C#如何实现简单的点餐系统”,给大家总结了以下内容,具有一定借鉴价值,内容详细步骤清晰,细节处理妥当,希望大家通过这篇文章有所收获,下面让我们一起来看看具体内容吧。
登录分为用户登录和管理员登录(店家),管理员有且只有一个账号可以登录。用户登录需要先注册,注册必须用手机号注册。
登录界面效果图
登录主要就是判断,多加些判断就行了
登录代码展示:
#region 窗体效果 public class Win32 { public const Int32 AW_HOR_POSITIVE = 0x00000001; // 从左到右打开窗口 public const Int32 AW_HOR_NEGATIVE = 0x00000002; // 从右到左打开窗口 public const Int32 AW_VER_POSITIVE = 0x00000004; // 从上到下打开窗口 public const Int32 AW_VER_NEGATIVE = 0x00000008; // 从下到上打开窗口 public const Int32 AW_CENTER = 0x00000010; //若使用了AW_HIDE标志,则使窗口向内重叠;若未使用AW_HIDE标志,则使窗口向外扩展。 public const Int32 AW_HIDE = 0x00010000; //隐藏窗口,缺省则显示窗口。 public const Int32 AW_ACTIVATE = 0x00020000; //激活窗口。在使用了AW_HIDE标志后不要使用这个标志。 public const Int32 AW_SLIDE = 0x00040000; //使用滑动类型。缺省则为滚动动画类型。当使用AW_CENTER标志时,这个标志就被忽略。 public const Int32 AW_BLEND = 0x00080000; //使用淡出效果。只有当hWnd为顶层窗口的时候才可以使用此标志。 [DllImport("user32.dll", CharSet = CharSet.Auto)] public static extern bool AnimateWindow( IntPtr hwnd, // handle to window int dwTime, // duration of animation int dwFlags // animation type ); } #endregion ValidCode validCode = new ValidCode(5, ValidCode.CodeType.Numbers);//实例化这个对象 //窗体加载 private void Login_Load(object sender, EventArgs e) { picValidCode.Image = Bitmap.FromStream(validCode.CreateCheckCodeImage());//点击图片更换验证码 Win32.AnimateWindow(this.Handle,500, Win32.AW_VER_POSITIVE);//窗体出现效果 } //验证码图片 private void picValidCode_Click(object sender, EventArgs e) { picValidCode.Image = Bitmap.FromStream(validCode.CreateCheckCodeImage());//点击图片更换验证码 } //注册 private void linkLabel2_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { Enroll EN = new Enroll(); this.Hide(); EN.ShowDialog(); Application.ExitThread(); } //登录按钮 private void LoginButton_Click(object sender, EventArgs e) { Saveusername.name = Username.Text; string sql = string.Format("select * from UserList where UserID='{0}'and UserPassword='{1} '", Username.Text, password.Text); SqlDataReader reader = DBHelper.GetDataReader(sql); if (Username.Text == "") { MessageBox.Show("请输入用户名!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Asterisk); } else if (password.Text == "") { MessageBox.Show("请输入密码!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Asterisk); } else if (!this.txtValidCode.Text.Equals(validCode.CheckCode))//验证是否输入正确 { MessageBox.Show(" 请输入正确的验证码!", this.Text); this.txtValidCode.Focus(); this.txtValidCode.Text = ""; reader.Close(); return; } else if (reader.Read()) { Saveusername.ID = reader["ID"].ToString();//获取ID用于个人中心修改信息 reader.Close(); if (Saveusername.name=="Sweet") { 管理员界面.GLY gLY = new 管理员界面.GLY(); this.Hide(); gLY.ShowDialog(); Application.ExitThread(); } XMB xMB = new XMB(); this.Hide(); xMB.ShowDialog(); Application.ExitThread(); } else { MessageBox.Show("用户名或密码输入错误!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error); } reader.Close(); picValidCode.Image = Bitmap.FromStream(validCode.CreateCheckCodeImage());//点击图片更换验证码 } //忘记密码 private void linkLabel1_LinkClicked_1(object sender, LinkLabelLinkClickedEventArgs e) { ForgetPwd forget = new ForgetPwd(); this.Hide(); forget.ShowDialog(); Application.ExitThread(); } #region 用于窗体移动 private Point mPoint;//定义一个位置信息Point用于存储鼠标位置 private void Login_MouseDown(object sender, MouseEventArgs e) { mPoint = new Point(e.X, e.Y); } private void Login_MouseMove(object sender, MouseEventArgs e) { if (e.Button == MouseButtons.Left) { this.Location = new Point(this.Location.X + e.X - mPoint.X, this.Location.Y + e.Y - mPoint.Y); } } #endregion private void Login_FormClosed(object sender, FormClosedEventArgs e) { Win32.AnimateWindow(this.Handle, 500, Win32.AW_BLEND|Win32.AW_HIDE); } private void pictureBox3_Click(object sender, EventArgs e) { this.Close(); } private void pictureBox4_Click(object sender, EventArgs e) { this.WindowState = FormWindowState.Minimized;//最小化 }
图片验证码代码展示:
public class ValidCode { #region Private Fields private const double PI = 3.1415926535897932384626433832795; private const double PI2 = 6.283185307179586476925286766559; //private readonly int _wordsLen = 4; private int _len; private CodeType _codetype; private readonly Single _jianju = (float)18.0; private readonly Single _height = (float)24.0; private string _checkCode; #endregion #region Public Property public string CheckCode { get { return _checkCode; } } #endregion #region Constructors /// <summary> /// public constructors /// </summary> /// <param name="len"> 验证码长度 </param> /// <param name="ctype"> 验证码类型:字母、数字、字母+ 数字 </param> public ValidCode(int len, CodeType ctype) { this._len = len; this._codetype = ctype; } #endregion #region Public Field public enum CodeType { Words, Numbers, Characters, Alphas } #endregion #region Private Methods private string GenerateNumbers() { string strOut = ""; System.Random random = new Random(); for (int i = 0; i < _len; i++) { string num = Convert.ToString(random.Next(10000) % 10); strOut += num; } return strOut.Trim(); } private string GenerateCharacters() { string strOut = ""; System.Random random = new Random(); for (int i = 0; i < _len; i++) { string num = Convert.ToString((char)(65 + random.Next(10000) % 26)); strOut += num; } return strOut.Trim(); } // private string GenerateAlphas() { string strOut = ""; string num = ""; System.Random random = new Random(); for (int i = 0; i < _len; i++) { if (random.Next(500) % 2 == 0) { num = Convert.ToString(random.Next(10000) % 10); } else { num = Convert.ToString((char)(65 + random.Next(10000) % 26)); } strOut += num; } return strOut.Trim(); } private System.Drawing.Bitmap TwistImage(Bitmap srcBmp, bool bXDir, double dMultValue, double dPhase) { System.Drawing.Bitmap destBmp = new Bitmap(srcBmp.Width, srcBmp.Height); // 将位图背景填充为白色 System.Drawing.Graphics graph = System.Drawing.Graphics.FromImage(destBmp); graph.FillRectangle(new SolidBrush(System.Drawing.Color.White), 0, 0, destBmp.Width, destBmp.Height); graph.Dispose(); double dBaseAxisLen = bXDir ? (double)destBmp.Height : (double)destBmp.Width; for (int i = 0; i < destBmp.Width; i++) { for (int j = 0; j < destBmp.Height; j++) { double dx = 0; dx = bXDir ? (PI2 * (double)j) / dBaseAxisLen : (PI2 * (double)i) / dBaseAxisLen; dx += dPhase; double dy = Math.Sin(dx); // 取得当前点的颜色 int nOldX = 0, nOldY = 0; nOldX = bXDir ? i + (int)(dy * dMultValue) : i; nOldY = bXDir ? j : j + (int)(dy * dMultValue); System.Drawing.Color color = srcBmp.GetPixel(i, j); if (nOldX >= 0 && nOldX < destBmp.Width && nOldY >= 0 && nOldY < destBmp.Height) { destBmp.SetPixel(nOldX, nOldY, color); } } } return destBmp; } #endregion #region Public Methods public Stream CreateCheckCodeImage() { string checkCode; switch (_codetype) { case CodeType.Alphas: checkCode = GenerateAlphas(); break; case CodeType.Numbers: checkCode = GenerateNumbers(); break; case CodeType.Characters: checkCode = GenerateCharacters(); break; default: checkCode = GenerateAlphas(); break; } this._checkCode = checkCode; MemoryStream ms = null; // if (checkCode == null || checkCode.Trim() == String.Empty) return null; Bitmap image = new System.Drawing.Bitmap((int)Math.Ceiling((checkCode.Length * _jianju)), (int)_height); Graphics g = Graphics.FromImage(image); try { Random random = new Random(); g.Clear(Color.White); // 画图片的背景噪音线 for (int i = 0; i < 18; i++) { int x1 = random.Next(image.Width); int x2 = random.Next(image.Width); int y1 = random.Next(image.Height); int y2 = random.Next(image.Height); g.DrawLine(new Pen(Color.FromArgb(random.Next()), 1), x1, y1, x2, y2); } Font font = new System.Drawing.Font("Times New Roman", 14, System.Drawing.FontStyle.Bold); LinearGradientBrush brush = new LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height), Color.Blue, Color.DarkRed, 1.2f, true); if (_codetype != CodeType.Words) { for (int i = 0; i < checkCode.Length; i++) { g.DrawString(checkCode.Substring(i, 1), font, brush, 2 + i * _jianju, 1); } } else { g.DrawString(checkCode, font, brush, 2, 2); } // 画图片的前景噪音点 for (int i = 0; i < 150; i++) { int x = random.Next(image.Width); int y = random.Next(image.Height); image.SetPixel(x, y, Color.FromArgb(random.Next())); } // 画图片的波形滤镜效果 if (_codetype != CodeType.Words) { image = TwistImage(image, true, 3, 1); } // 画图片的边框线 g.DrawRectangle(new Pen(Color.Silver), 0, 0, image.Width - 1, image.Height - 1); ms = new System.IO.MemoryStream(); image.Save(ms, System.Drawing.Imaging.ImageFormat.Gif); } finally { g.Dispose(); image.Dispose(); } return ms; } #endregion
注册界面效果图
注册界面代码展示
短信验证码,用接口就能实现
TimeSpan dtTo = new TimeSpan(0, 0, 60);//设置计时器的开始时间 int value;//用来存储随机数 public Enroll() { InitializeComponent(); } //获取短信验证码 private void CodeButton_Click(object sender, EventArgs e) { Regex rx = new Regex(@"^0{0,1}(13[0-9]|15[0-9]|15[0-9]|18[0-9]|17[0-9])[0-9]{8}$"); if (!rx.IsMatch(EnrollTel.Text)) { EnrollTel.Text = ""; MessageBox.Show("手机号格式不正确,请重新输入", "提示", MessageBoxButtons.OK, MessageBoxIcon.Asterisk); } else { Random rad = new Random();//实例化随机数产生器rad; value = rad.Next(1000, 10000);//用rad生成大于等于1000,小于等于9999的随机数; Note.NoTe(EnrollTel.Text, value); timer1.Start(); dtTo = new TimeSpan(0, 0, 60); } } //时间控件用来实现60秒倒计时 private void timer1_Tick_1(object sender, EventArgs e) { CodeButton.Enabled = false; dtTo = dtTo.Subtract(new TimeSpan(0, 0, 1));//每隔一秒减一 CodeButton.Text = "(" + dtTo.Seconds.ToString() + ")" + "重新获取"; if (dtTo.TotalSeconds == 0.0)//当倒计时完毕 { this.CodeButton.Enabled = true; CodeButton.Text = "点击获取验证码"; this.timer1.Stop(); timer1.Dispose(); } } //注册按钮 private void FinishButton_Click(object sender, EventArgs e) { bool Bool = Fac(); if (Bool) { string type = "普通用户"; string sex = ""; if (RadioMan.Checked)//判断单选按钮的text { sex = RadioMan.Text; } else if (RadioWoman.Checked) { sex = RadioWoman.Text; } string sql = string.Format("insert into UserList values('{0}','{1}','{2}','{3}','{4}','{5}')", EnrollUser.Text, EnrollPwd.Text, sex, EnrollTel.Text, EnrollAddress.Text, type); bool sqlinsert = DBHelper.ExecuteNonQuery(sql); if (sqlinsert) { DialogResult result = MessageBox.Show("注册成功!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Question); this.Hide(); Login LG = new Login(); LG.ShowDialog(); } } else { return; } } /// <summary> /// 用于注册界面里格式的判断 /// </summary> /// <returns></returns> private bool Fac() { string sql = string.Format("select * from UserList where UserID='{0}'", EnrollUser.Text); SqlDataReader reader = DBHelper.GetDataReader(sql); if (EnrollUser.Text == "") { MessageBox.Show("用户名不能为空!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Asterisk); reader.Close(); return false; } else if (EnrollPwd.Text == "") { MessageBox.Show("请输入密码!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Asterisk); reader.Close(); return false; } else if (EnrollPwd.Text != EnrollPwdY.Text) { MessageBox.Show("两次密码必须一样!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Asterisk); reader.Close(); return false; } else if (EnrollTel.Text == "") { MessageBox.Show("请输入手机号!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Asterisk); reader.Close(); return false; } else if (EtxtValidCode.Text == "") { MessageBox.Show("请输入验证码!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Asterisk); reader.Close(); return false; } else if (int.Parse(EtxtValidCode.Text) != value) { MessageBox.Show("请输入正确的验证码!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Asterisk); reader.Close(); return false; } else if (reader.Read()) { DialogResult result = MessageBox.Show("此用户已存在,是否前往登录?", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question); if (result == DialogResult.Yes) { Login LG = new Login(); LG.ShowDialog(); reader.Close(); this.Close(); return false; } else { reader.Close(); return false; } } else { reader.Close(); return true; } } //窗体加载事件 private void Enroll_Load(object sender, EventArgs e) { CodeButton.Text = "点击获取验证码"; timer1.Interval = 1000;//设置每次间隔一秒 }
忘记密码界面效果图
下面为用户界面的展示
简单介绍一下:由于菜品是有很多的而且不确定数量,所以必须动态加载,不能拖图片控件等。
用户功能实现思路:首先要知道每个用户只能看自己的,所以在登录时候就必须用一个东西接收用户输入的名字,以便在主界面显示出与该用户相匹配的数据。
购物车界面
购物车首先要有一个购物车表用来存储用户添加的商品,当用户结账以后,购物车表中该用户的信息就应全部清除。然后为该用户生成订单(存入信息到订单表),并将用户购买的商品存入订单详情表中。
动态加载菜品代码展示
private void XMB_Load(object sender, EventArgs e) { /*SetStyle(ControlStyles.UserPaint, true); SetStyle(ControlStyles.AllPaintingInWmPaint, true); // 禁止擦除背景. SetStyle(ControlStyles.DoubleBuffer, true); // 双缓冲*/ linke_热菜.LinkColor = Color.Gray; Win32.AnimateWindow(this.Handle, 500, Win32.AW_CENTER);//窗体出现效果 Order_pl.Visible = false; Or_panel1.Visible = false;//隐藏订单控件 menu_all_全部.AutoScroll = true;//添加滚动条 this.toolStripStatusLabel1.Font = new Font("微软雅黑", 12, FontStyle.Bold); toolStripStatusLabel1.Text = string.Format("欢迎“{0}”使用Sweet点餐系统! ", Saveusername.name); this.timer2.Start(); string sql = "select * from Food_table"; DataSet ds = DBHelper.GetDataSet(sql); int xx = 0; int yy = 0; for (int i = 0; i < ds.Tables[0].Rows.Count; i++) { Label FoodName = new Label(); Label FoodPrice = new Label(); PictureBox picture = new PictureBox(); Button button = new Button();//创建控件 FoodName.Name = "FoodName_" + i; FoodPrice.Name = "FoodPrice_" + i; picture.Name = "picture_" + i; button.Name = ds.Tables[0].Rows[i]["FoodID"].ToString();//加入购物车按钮命名为菜品表的FoodID FoodName.Text = ds.Tables[0].Rows[i]["FoodName"].ToString(); FoodPrice.Text = "¥" + ds.Tables[0].Rows[i]["FoodPrice"].ToString() + "/份";//控件text属性赋值 button.Text = "加入购物车"; FoodName.AutoSize = true; FoodPrice.AutoSize = true; button.AutoSize = true; FoodName.Font = new Font("微软雅黑", 11); FoodPrice.Font = new Font("微软雅黑", 11); button.Font = new Font("微软雅黑", 6); button.BackColor = Color.Gray; button.ForeColor = Color.Transparent; button.FlatStyle = FlatStyle.Flat; button.Size = new Size(60, 10); picture.Location = new Point(100 * xx, 20 + yy); FoodName.Location = new Point(100 * xx, 100 + yy); FoodPrice.Location = new Point(100 * xx, 120 + yy); button.Location = new Point(100 * xx, 140 + yy);//控件定位 picture.Image = Image.FromFile(Application.StartupPath + @"\FoodPhoto\" + ds.Tables[0].Rows[i]["PhotoName"].ToString());//显示图片,路径为可执行文件所在文件夹的FoodPhoto文件夹内的图片 picture.SizeMode = PictureBoxSizeMode.StretchImage; picture.Size = new Size(150, 80); picture.BorderStyle = BorderStyle.FixedSingle; button.Cursor = Cursors.Hand; button.Click += new EventHandler(this.Button_Click); menu_all_全部.Controls.Add(FoodName); menu_all_全部.Controls.Add(FoodPrice); menu_all_全部.Controls.Add(picture); menu_all_全部.Controls.Add(button);//把控件绑定到panel中 xx++; if (xx++ >= 4) { xx = 0; yy += 180; } } }
动态加载菜品解决窗体控件闪烁问题代码展示
protected override CreateParams CreateParams//解决窗体控件闪烁问题 { get { CreateParams cp = base.CreateParams; cp.ExStyle |= 0x02000000; return cp; } }
加入购物车按钮代码展示
#region 购物车 private void 购物车_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { // 禁止用户改变DataGridView1的所有列的列宽 dataGridView1.AllowUserToResizeColumns = false; //禁止用户改变DataGridView1所有行的行高 dataGridView1.AllowUserToResizeRows = false; dataGridView1.Columns[0].ReadOnly = true; //禁止用户编辑第一列 dataGridView1.Columns[1].ReadOnly = true; //禁止用户编辑第二列 dataGridView1.Columns[2].ReadOnly = true;//禁止用户编辑第三列 this.dataGridView1.AllowUserToResizeColumns = false; //禁止用户拖动标题宽度 dataGridView1.AutoGenerateColumns = false;//取消自动生成列 dataGridView1.RowHeadersVisible = false; //隐藏前面空白选择部分 string sql = string.Format("select FoodName,ShoppingCount,ShoppingPrice,ShoppingID from Food_table join Shopping_table on Food_table.FoodID=Shopping_table.FoodID join UserList on '{0}'=Shopping_table.UserID where UserList.UserID='{1}'", Saveusername.name,Saveusername.name);//三表查询 dataGridView1.DataSource = DBHelper.GetDataSet(sql).Tables[0]; double SumPrice = 0;//用来存储总金额 if (DBHelper.GetDataSet(sql).Tables[0].Rows.Count > 0) { for (int i = 0; i < DBHelper.GetDataSet(sql).Tables[0].Rows.Count; i++) { SumPrice += double.Parse(DBHelper.GetDataSet(sql).Tables[0].Rows[i][2].ToString()); } Money_label.Text = "¥" + SumPrice.ToString() + "元"; } dataGridView1.ClearSelection(); //取消默认选中 if (show_shopping_pl.Visible == true) { show_shopping_pl.Visible = false; } else { show_shopping_pl.Visible = true; } if (Or_panel1.Visible == true) { Or_panel1.Visible = false; } if (Order_pl.Visible == true) { Order_pl.Visible = false; } } //清空购物车 private void delete_label_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { DialogResult result = MessageBox.Show("是否清空购物车", "提示信息", MessageBoxButtons.OKCancel, MessageBoxIcon.Asterisk); if (result == DialogResult.OK) { string sql = string.Format("delete from Shopping_table where UserID='{0}'", Saveusername.name); if (DBHelper.ExecuteNonQuery(sql)) { sql = string.Format("select FoodName,ShoppingCount,ShoppingPrice,ShoppingID from Food_table join Shopping_table on Food_table.FoodID=Shopping_table.FoodID join UserList on '{0}'=Shopping_table.UserID ", Saveusername.name); dataGridView1.DataSource = DBHelper.GetDataSet(sql); dataGridView1.AllowUserToAddRows = false; Money_label.Text = "¥0元"; MessageBox.Show("成功清空购物车!", "提示", MessageBoxButtons.OK); } } } #endregion
主界面结账功能界面
结账部分代码展示
private void Yes_Order_Load(object sender, EventArgs e) { Or_label1.Text = "["+Saveusername.name+"]" + ">确认购买"; dataGridView1.RowHeadersVisible = false; //隐藏前面空白选择部分 // // 禁止用户改变DataGridView1的所有列的列宽 //dataGridView1.AllowUserToResizeColumns = false; 禁止用户改变DataGridView1所有行的行高 //dataGridView1.AllowUserToResizeRows = false; dataGridView1.Columns[0].ReadOnly = true; //禁止用户编辑第一列 dataGridView1.Columns[1].ReadOnly = true; //禁止用户编辑第二列 dataGridView1.Columns[2].ReadOnly = true;//禁止用户编辑第三列 this.dataGridView1.AllowUserToResizeColumns = false; //禁止用户拖动标题宽度 dataGridView1.AutoGenerateColumns = false;//取消自动生成列 dataGridView1.RowHeadersVisible = false; //隐藏前面空白选择部分 string sql = string.Format("select FoodName,ShoppingCount,ShoppingPrice,ShoppingID from Food_table join Shopping_table on Food_table.FoodID=Shopping_table.FoodID join UserList on '{0}'=Shopping_table.UserID where UserList.UserID='{1}'", Saveusername.name,Saveusername.name);//三表查询 dataGridView1.DataSource = DBHelper.GetDataSet(sql).Tables[0]; SumPrice = 0;//用来存储总金额 if (DBHelper.GetDataSet(sql).Tables[0].Rows.Count > 0) { for (int i = 0; i < DBHelper.GetDataSet(sql).Tables[0].Rows.Count; i++) { SumPrice += double.Parse(DBHelper.GetDataSet(sql).Tables[0].Rows[i][2].ToString()); } Money_label.Text = "¥" + SumPrice.ToString() + "元"; } dataGridView1.ClearSelection(); //取消默认选中 string sql_1 = string.Format("select * from UserList where UserID='{0}'",Saveusername.name); DataSet ds = DBHelper.GetDataSet(sql_1); Name_label.Text = ds.Tables[0].Rows[0]["UserID"].ToString()+":"; Tel_label.Text = ds.Tables[0].Rows[0]["UserTel"].ToString(); Address_label.Text = ds.Tables[0].Rows[0]["UserAddress"].ToString(); Yes_Money_label.Text = Money_label.Text; } private void Yes_pay_btn_Click(object sender, EventArgs e) { if (Address_label.Text=="") { MessageBox.Show("地址信息不完整,请填写完整!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information); return; } string Order_Data = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss"); //下单日期 string OrderNumber = DateTime.Now.ToString("yyyyMMddhhmmss");//订单编号 string sql = string.Format("select * from Shopping_table where UserID='{0}'",Saveusername.name);//查询购物车表 DataTable table_shopping = DBHelper.GetDataSet(sql).Tables[0]; if (table_shopping.Rows.Count>0)//购物车有数据就创建订单 { string sql_order = string.Format("insert into Order_table values('{0}','{1}','{2}','{3}','{4}','{5}')",OrderNumber,Saveusername.name,SumPrice,Address_label.Text,Order_Data,Tel_label.Text);//创建订单 string sql_state = string.Format("insert into OrderState_table values('{0}','{1}')",OrderNumber,"等待确认");//订单状态 if (DBHelper.ExecuteNonQuery(sql_order)&&DBHelper.ExecuteNonQuery(sql_state)) { sql_order = string.Format("select top 1 * from Order_table where UserID='{0}' order by OrderID desc",Saveusername.name); DataTable table_order = DBHelper.GetDataTable(sql_order); for (int i = 0; i < table_shopping.Rows.Count; i++)//把数据逐条插入订单详情表 { string sql_datailde = string.Format("insert into Datailedorder_table values('{0}','{1}','{2}','{3}')", int.Parse(table_shopping.Rows[i]["FoodID"].ToString()),int.Parse(table_shopping.Rows[i]["ShoppingCount"].ToString()),double.Parse(table_shopping.Rows[i]["ShoppingPrice"].ToString()),int.Parse(table_order.Rows[0]["OrderID"].ToString())); //try //{ DBHelper.ExecuteNonQuery(sql_datailde); //} /* catch (Exception) { MessageBox.Show("异常"); return }*/ } string sql_delete = string.Format("delete from Shopping_table where UserID='{0}'",Saveusername.name); DBHelper.ExecuteNonQuery(sql_delete);//创建订单后清空购物车 DialogResult result= MessageBox.Show("支付成功", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information); if (result==DialogResult.OK) { string sql_select = string.Format("select * from Shopping_table where UserID='{0}'",Saveusername.name); dataGridView1.DataSource = DBHelper.GetDataSet(sql_select).Tables[0]; Money_label.Text = "¥0元"; Yes_Money_label.Text = "¥0元"; XMB.GetXMB.Money_label.Text = "¥0元"; Order_Form order_ = new Order_Form(); XMB.GetXMB.Or_from(order_); return; } } } else { MessageBox.Show("未选择菜品", "提示", MessageBoxButtons.OK, MessageBoxIcon.Asterisk); } }
订单功能界面
点击订单,出现订单详情
订单功能部分代码
private void Order_Form_Load(object sender, EventArgs e) { OR_panel.AutoScroll = true;//添加滚动条 int xx = 0; int yy = 0; string sql = string.Format("select * from Order_table where UserID='{0}'",Saveusername.name); DataTable Or_table = DBHelper.GetDataTable(sql); DataTable State = DBHelper.GetDataTable(string.Format("select OrderState from OrderState_table join Order_table on Order_table.OrderNumber=OrderState_table.OrderNumber where Order_table.UserID='{0}'",Saveusername.name)); for (int i = 0; i < Or_table.Rows.Count; i++) { Label OrderNumber = new Label();//编号 Label ShoppingPrice = new Label();//价格 Label SaleDate = new Label();//时间 Label OrderState = new Label();//状态 Label sweet = new Label(); Panel panel = new Panel(); PictureBox Db = new PictureBox(); //实例化一个控件 Db.Name = "Db_PictureBox" + i;//设定名称 OrderNumber.Name = "Label" + i; ShoppingPrice.Name = "Label" + i; SaleDate.Name = "Label" + i; OrderState.Name = "Label" + i; sweet.Name = "Label" + i; panel.Name = "Panel" + i;//设定名称 panel.Text = Or_table.Rows[i]["OrderID"].ToString();//把订单ID赋给控件的Text,以便取消订单 SaleDate.Text = Or_table.Rows[i]["SaleDate"].ToString(); ShoppingPrice.Text = " ¥ " + Or_table.Rows[i]["ShoppingPrice"].ToString(); OrderNumber.Text = "订单编号: " + Or_table.Rows[i]["OrderNumber"].ToString(); sweet.Text = "Sweet点餐"; OrderState.Text = State.Rows[i]["OrderState"].ToString(); sweet.Location = new Point(150,30); ShoppingPrice.Location = new Point(480,30); OrderState.Location = new Point(595,30); SaleDate.Location = new Point(150,70); OrderNumber.Location = new Point(450,70); Db.Location = new Point(15, 10 + yy);//设定位置 panel.Location = new Point(5, 0 + yy);//设定位置 sweet.AutoSize = true; OrderState.AutoSize = true; ShoppingPrice.AutoSize = true; SaleDate.AutoSize = true; OrderNumber.AutoSize = true; Db.Image = Image.FromFile(Application.StartupPath + @"\FoodPhoto\" + "sezhi.png"); Db.SizeMode = PictureBoxSizeMode.StretchImage; //设定图像如何显示 sweet.Font = new Font("微软雅黑", 11); OrderNumber.Font = new Font("微软雅黑", 11); OrderState.Font = new Font("微软雅黑", 11); ShoppingPrice.Font = new Font("微软雅黑", 11); SaleDate.Font = new Font("微软雅黑", 11); Db.Size = new Size(80, 80); panel.Size = new Size(683, 100); Db.BorderStyle = BorderStyle.FixedSingle; //设置边框样式 panel.BorderStyle = BorderStyle.FixedSingle; //设置边框样式 panel.BackColor = Color.White; SaleDate.ForeColor = Color.Red; ShoppingPrice.ForeColor = Color.Red; OrderNumber.ForeColor = Color.Green; OrderState.ForeColor = Color.Green; panel.Cursor = Cursors.Hand; OR_panel.Controls.Add(Db); OR_panel.Controls.Add(panel); panel.Controls.Add(OrderState); panel.Controls.Add(sweet); panel.Controls.Add(OrderNumber); panel.Controls.Add(SaleDate); panel.Controls.Add(ShoppingPrice); panel.Click += new EventHandler(this.panel1_MouseClick); //添加单击事件 panel.MouseEnter += new EventHandler(this.panel1_MouseEnter); //添加单击事件 panel.MouseLeave += new EventHandler(this.panel1_MouseLeave); //添加单击事件 xx++; if (xx++ >= 1) { yy += 110; //aa += 10; } } }
接下来是管理员界面展示
1.菜品管理界面
菜品管理添加菜品关键代码
private void Food_in_tbn_Click(object sender, EventArgs e) { if (Fag() == false) return; string FilePath = Application.StartupPath + @"\FoodPhoto";//获取可执行文件所在位置的FoodPhoto文件夹路径 if (Directory.Exists(FilePath) == false) { //判断文件夹是否存在如果不存在创建文件夹 Directory.CreateDirectory(FilePath);//创建文件夹 } string FileName = DateTime.Now.ToString("yyyyMMddhhmmss") + new Random().Next(1000, 9999); //以当前时间和1000到9999的随机数合起来作为文件的名字 FileName += nj.Substring(nj.LastIndexOf("."));//截取图片的后缀名 File.Copy(nj, FilePath + @"\" + FileName);//把图片复制到FoodPhoto文件夹 string SQLst = string.Format("insert into Food_table values('{0}','{1}','{2}','{3}')", Add_Food_tb.Text,Add_money_tb.Text,Add_type_ctb.Text, FileName); if (DBHelper.ExecuteNonQuery(SQLst)) { MessageBox.Show("菜品添加成功", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information); } else { MessageBox.Show("保存失败", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error); } } public static string nj; public static string name; private void pictureBox1_Click(object sender, EventArgs e) { //打开资源管理器选择图片 OpenFileDialog openFileDialog1 = new OpenFileDialog(); nj = ""; name = ""; if (openFileDialog1.ShowDialog() == DialogResult.OK) { nj = openFileDialog1.FileName; pictureBox1.Image = Image.FromFile(nj); } }
2.订单管理界面
主要实现思路:动态加载控件,控件定位,查询数据库,修改表信息
3.销售统计界面
点击确认订单后会生成一个订单,效果图如下:
代码展示
private void Button_Click(object sender, EventArgs e) { Button button = (Button)sender;//将触发此事件的对象转换为该对象 OrderID = int.Parse(button.Name.ToString()); string FilePath = @"D:\订单票据";//获取可执行文件所在位置的FoodPhoto文件夹路径 if (Directory.Exists(FilePath) == false) { //判断文件夹是否存在如果不存在创建文件夹 Directory.CreateDirectory(FilePath);//创建文件夹 } string sql_12 = string.Format("select * from Order_table where OrderID='{0}'", OrderID); DataTable piao = DBHelper.GetDataTable(sql_12); for (int i = 0; i < piao.Rows.Count; i++) { StreamWriter sw = new StreamWriter(@"D:\订单票据\Sweet点餐"+piao.Rows[0]["OrderNumber"].ToString()+".txt"); string a = "订单编号:"+piao.Rows[i]["OrderNumber"].ToString(); string b = "订单内容:"; sw.WriteLine(a); sw.WriteLine("-------------------------------------------"); sw.WriteLine(b); string sql_13 = "select Food_table.FoodName,Datailedorder_table.ShoppingCount,Datailedorder_table.ShoppingPrice from Order_table join Datailedorder_table on Datailedorder_table.OrderID=Order_table.OrderID join Food_table on Food_table.FoodID=Datailedorder_table.FoodID where Order_table.OrderNumber='" + piao.Rows[i]["OrderNumber"] + "'";//查找需要的菜品名称,菜品购买的数量,每一种菜品购买的总金额 DataTable table = DBHelper.GetDataTable(sql_13); for (int j = 0; j < table.Rows.Count; j++) { string FoodName = table.Rows[i]["FoodName"].ToString(); string FoodCount = table.Rows[i]["ShoppingCount"].ToString(); string ShoppingPrice = table.Rows[i]["ShoppingPrice"].ToString(); sw.Write(" {0}",FoodName); sw.Write(" x{0}", FoodCount); sw.WriteLine(" {0}",ShoppingPrice); } sw.WriteLine("-------------------------------------------"); string sum = "总计:"+piao.Rows[i]["ShoppingPrice"].ToString(); string c = "联系地址:"; string Address = "联系地址:"+piao.Rows[i]["Address"].ToString(); string User = "联系人:"+piao.Rows[i]["UserID"].ToString(); string tel = "联系电话:"+piao.Rows[i]["UserTel"].ToString(); sw.WriteLine(sum); sw.WriteLine(); sw.WriteLine(c); sw.WriteLine("-------------------------------------------"); sw.WriteLine(User); sw.WriteLine(tel); sw.WriteLine(Address); sw.Close(); }
C#是一个简单、通用、面向对象的编程语言,它由微软Microsoft开发,继承了C和C++强大功能,并且去掉了一些它们的复杂特性,C#综合了VB简单的可视化操作和C++的高运行效率,以其强大的操作能力、优雅的语法风格、创新的语言特性和便捷的面向组件编程从而成为.NET开发的首选语言,但它不适用于编写时间急迫或性能非常高的代码,因为C#缺乏性能极高的应用程序所需要的关键功能。
感谢您的阅读,希望您对“C#如何实现简单的点餐系统”这一关键问题有了一定的理解,具体使用情况还需要大家自己动手实验使用过才能领会,快去试试吧,如果想阅读更多相关知识点的文章,欢迎关注亿速云行业资讯频道!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。