Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to implement a simple ordering system in C #

2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article "C# how to achieve a simple ordering system" is not understood by most people except programmers. Today, in order to make you better understand "how to achieve a simple ordering system in C#", the editor summarizes the following content, which has a certain reference value. The detailed steps are clear and the details are handled properly. I hope you can get something through this article. Let's take a look at the specific content.

1. Login registration module

Login is divided into user login and administrator login (store), the administrator has and only one account can log in. Users need to register first, and registration must be made with their mobile phone number.

Effect diagram of login interface

Login is mainly judgment. Just add more judgment.

Login code display:

# region forms effects public class Win32 {public const Int32 AW_HOR_POSITIVE = 0x00000001; / / Open window public const Int32 AW_HOR_NEGATIVE = 0x00000002 from left to right; / / Open window public const Int32 AW_VER_POSITIVE = 0x00000004 from right to left; / / Open window public const Int32 AW_VER_NEGATIVE = 0x00000008 from top to bottom / / Open the window public const Int32 AW_CENTER = 0x00000010 from bottom to top; / / if the AW_HIDE flag is used, make the window overlap inward If the AW_HIDE flag is not used, the window is expanded outward. Public const Int32 AW_HIDE = 0x00010000; / / the window is hidden and displayed by default. Public const Int32 AW_ACTIVATE = 0x00020000; / / activate the window. Do not use the AW_HIDE flag after using it. Public const Int32 AW_SLIDE = 0x00040000; / / use the sliding type. The default is the rolling animation type. When using the AW_CENTER flag, this flag is ignored. Public const Int32 AW_BLEND = 0x000800000; / / use the fade-out effect. This flag can only be used when hWnd is the top-level window. [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) / / instantiate this object / / the form loads private void Login_Load (object sender, EventArgs e) {picValidCode.Image = Bitmap.FromStream (validCode.CreateCheckCodeImage ()); / / Click the picture to change the verification code Win32.AnimateWindow (this.Handle,500, Win32.AW_VER_POSITIVE) / / form effect} / / Verification code picture private void picValidCode_Click (object sender, EventArgs e) {picValidCode.Image = Bitmap.FromStream (validCode.CreateCheckCodeImage ()); / / Click the picture to change the verification code} / / register private void linkLabel2_LinkClicked (object sender, LinkLabelLinkClickedEventArgs e) {Enroll EN = new Enroll () This.Hide (); EN.ShowDialog (); Application.ExitThread ();} / / login button 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 ("Please enter a user name!" , "prompt", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);} else if (password.Text = = "") {MessageBox.Show ("Please enter the password!" , "prompt", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);} else if (! this.txtValidCode.Text.Equals (validCode.CheckCode)) / / verify that the correct input {MessageBox.Show ("Please enter the correct CAPTCHA!", this.Text); this.txtValidCode.Focus (); this.txtValidCode.Text = "" Reader.Close (); return;} else if (reader.Read ()) {Saveusername.ID = reader ["ID"] .ToString (); / / get ID for personal center modification information reader.Close () If (Saveusername.name== "Sweet") {Administrator interface .GLY gLY = new administrator interface .GLY (); this.Hide (); gLY.ShowDialog (); Application.ExitThread ();} XMB xMB = new XMB () This.Hide (); xMB.ShowDialog (); Application.ExitThread ();} else {MessageBox.Show ("wrong user name or password!" , "prompt", MessageBoxButtons.OK, MessageBoxIcon.Error);} reader.Close (); picValidCode.Image = Bitmap.FromStream (validCode.CreateCheckCodeImage ()); / / Click the picture to change the CAPTCHA} / / forget the password private void linkLabel1_LinkClicked_1 (object sender, LinkLabelLinkClickedEventArgs e) {ForgetPwd forget = new ForgetPwd (); this.Hide () Forget.ShowDialog (); Application.ExitThread ();} # region for form mobile private Point mPoint;// defines a location information Point is used to store mouse position 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.e-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;// minimization}

Picture CAPTCHA code display:

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 / public constructors / CAPTCHA length / CAPTCHA type: letters, numbers, alphanumeric 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; } } /// /// 用于注册界面里格式的判断 /// /// 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;}

Dynamic loading of dishes to solve the flicker problem of form controls Code display

Protected override CreateParams CreateParams// solves the flicker problem of form controls {get {CreateParams cp = base.CreateParams; cp.ExStyle | = 0x02000000; return cp;}}

Add shopping cart button code display

# region shopping cart private void shopping cart _ LinkClicked (object sender, LinkLabelLinkClickedEventArgs e) {/ / prohibit users from changing the column width of all columns of DataGridView1 dataGridView1.AllowUserToResizeColumns = false; / / prohibit users from changing the row height of all rows of DataGridView1 dataGridView1.AllowUserToResizeRows = false; dataGridView1.Columns [0] .ReadOnly = true / / prohibit users from editing the first column dataGridView1.Columns [1] .ReadOnly = true;// prohibit users from editing the second column dataGridView1.Columns [2] .ReadOnly = true;// prohibit users from editing the third column this.dataGridView1.AllowUserToResizeColumns = false;// prohibit users from dragging header width dataGridView1.AutoGenerateColumns = false;// to cancel automatic generation of columns dataGridView1.RowHeadersVisible = false / / hide the previous blank selections 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); / / query dataGridView1.DataSource = DBHelper.GetDataSet (sql) .Tables [0]; double SumPrice = 0 / / used to store the total amount 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+"]" + ">

Confirm purchase "; dataGridView1.RowHeadersVisible = false; / / hide the previous blank selections / prohibit users from changing the column widths of all columns of DataGridView1 / / dataGridView1.AllowUserToResizeColumns = false; prohibit users from changing the row heights of all rows of DataGridView1 / / dataGridView1.AllowUserToResizeRows = false DataGridView1.Columns [0] .ReadOnly = true;// forbids users to edit the first column dataGridView1.Columns [1] .ReadOnly = true;// forbids users to edit the second column dataGridView1.Columns [2] .ReadOnly = true;// forbids users to edit the third column this.dataGridView1.AllowUserToResizeColumns = false; / / forbids users to drag the title width dataGridView1.AutoGenerateColumns = false / / cancel the auto-generated column dataGridView1.RowHeadersVisible = false; / / hide the previous blank selections 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) / / three tables query dataGridView1.DataSource = DBHelper.GetDataSet (sql). Tables [0]; SumPrice = 0 sql / to store the total amount 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) / / create an order {string sql_order = string.Format if the shopping cart has data ("insert into Order_table values ('{0}','{1}','{2}','{3}','{4}','{5}')", OrderNumber,Saveusername.name,SumPrice,Address_label.Text,Order_Data,Tel_label.Text) / / create order string sql_state = string.Format ("insert into OrderState_table values ('{0}','{1}')", OrderNumber, "waiting for confirmation") / / order status 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;}

Next is the administrator interface display.

1. Food management interface

Add key codes for dishes management

Private void Food_in_tbn_Click (object sender, EventArgs e) {if (Fag () = = false) return; string FilePath = Application.StartupPath + @ "\ FoodPhoto" / / get the FoodPhoto folder path of the location of the executable file if (Directory.Exists (FilePath) = = false) {/ / determine whether the folder exists if there is no creation folder Directory.CreateDirectory (FilePath) / / create a folder} string FileName = DateTime.Now.ToString ("yyyyMMddhhmmss") + new Random () .Next (1000, 9999); / / take the current time and a random number from 1000 to 9999 as the file name FileName + = nj.Substring ("."); / / the suffix name of the intercepted image File.Copy (nj, FilePath + @ "\" + FileName) / / copy the picture to the FoodPhoto folder 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 ("Food added successfully", "prompt", MessageBoxButtons.OK, MessageBoxIcon.Information);} else {MessageBox.Show ("Save failed", "error", MessageBoxButtons.OK, MessageBoxIcon.Error) }} public static string nj; public static string name; private void pictureBox1_Click (object sender, EventArgs e) {/ / Open Explorer Select picture OpenFileDialog openFileDialog1 = new OpenFileDialog (); nj = ""; name = "" If (openFileDialog1.ShowDialog () = = DialogResult.OK) {nj = openFileDialog1.FileName; pictureBox1.Image = Image.FromFile (nj);}}

two。 Order management interface

The main implementation ideas: dynamically load controls, control positioning, query database, modify table information

3. Sales statistics interface

After clicking to confirm the order, an order will be generated. The effect picture is as follows:

Code presentation

Private void Button_Click (object sender, EventArgs e) {Button button = (Button) sender;// converts the object that triggered this event to the object OrderID = int.Parse (button.Name.ToString ()); string FilePath = @ "D:\ order ticket" / / get the FoodPhoto folder path of the location of the executable file if (Directory.Exists (FilePath) = = false) {/ / determine whether the folder exists if there is no creation folder Directory.CreateDirectory (FilePath) / / create folder} 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) StreamWriter sw +) {StreamWriter sw = new StreamWriter (@ "D:\ order ticket\ Sweet order" + piao.Rows [0] ["OrderNumber"] .ToString () + ".txt"); string a = "order number:" + piao.Rows [I] ["OrderNumber"] .ToString (); string b = "order content:"; 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"] + "'" / / find the name of the dish you need, the quantity purchased, and the total amount of each item purchased DataTable table = DBHelper.GetDataTable (sql_13); for (int j = 0; j < table.Rows.Count; jacks +) {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 = "Total:" + piao.Rows [I] ["ShoppingPrice"] .ToString (); string c = "contact address:"; string Address = "contact address:" + piao.Rows [I] ["Address"] .ToString (); string User = "contact:" + piao.Rows [I] ["UserID"] .ToString () String tel = "contact: + 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 () What is C #? C # is a simple, general-purpose, object-oriented programming language developed by Microsoft Microsoft. It inherits the powerful functions of C and C++, and removes some of their complex features. C # combines the simple visualization of VB and the high efficiency of C++. Because of its strong operational ability, elegant syntax style, innovative language features and convenient component-oriented programming, it has become the preferred language for .NET development, but it is not suitable for writing code with urgent time or very high performance. because C# lacks the key features needed for high-performance applications.

Thank you for your reading. I hope you have a certain understanding of the key issue of "how to achieve a simple ordering system for C#". The specific usage still needs to be understood by everyone through hands-on experiments. Go and try it. If you want to read more articles on relevant knowledge points, welcome to follow the industry information channel!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report