11.22销售管理
using System; using System.Data.SqlClient; using System.Windows.Forms; using System.Collections.Generic; using System.Drawing; namespace SnacksInventorySystem { public partial class FormSalesManagement : Form { private List<Goods> goodsList; public FormSalesManagement() { InitializeComponent(); InitializeUI(); LoadGoodsData(); } private void InitializeUI() { // 设置窗口标题 Text = "销售管理"; // 设置窗口大小 Width = 600; Height = 400; // 设置窗口起始位置为屏幕中央 StartPosition = FormStartPosition.CenterScreen; // 创建销售日期选择器 dateTimePickerSalesDate = new DateTimePicker(); dateTimePickerSalesDate.Location = new Point(20, 20); dateTimePickerSalesDate.Width = 150; // 创建商品下拉框 comboBoxGoods = new ComboBox(); comboBoxGoods.Location = new Point(200, 20); comboBoxGoods.Width = 150; // 创建销售数量输入框 textBoxQuantity = new TextBox(); textBoxQuantity.Location = new Point(20, 60); textBoxQuantity.Width = 100; // 创建商品单价输入框 textBoxUnitPrice = new TextBox(); textBoxUnitPrice.Location = new Point(200, 60); textBoxUnitPrice.Width = 100; // 创建销售总金额显示框(只读) textBoxTotalAmount = new TextBox(); textBoxTotalAmount.Location = new Point(380, 60); textBoxTotalAmount.Width = 100; textBoxTotalAmount.ReadOnly = true; // 创建添加销售记录按钮 Button buttonAddSales = new Button(); buttonAddSales.Text = "添加销售记录"; buttonAddSales.Location = new Point(20, 100); buttonAddSales.Click += buttonAddSales_Click; // 创建查看销售记录按钮 Button buttonViewSales = new Button(); buttonViewSales.Text = "查看销售记录"; buttonViewSales.Location = new Point(200, 100); buttonViewSales.Click += buttonViewSales_Click; // 创建用于显示销售记录列表的DataGridView(可根据实际需求添加更多列显示详细信息) dataGridViewSales = new DataGridView(); dataGridViewSales.Location = new Point(20, 140); dataGridViewSales.Width = 560; dataGridViewSales.Height = 200; dataGridViewSales.Columns.Add("SalesDate", "销售日期"); dataGridViewSales.Columns.Add("GoodsName", "商品名称"); dataGridViewSales.Columns.Add("Quantity", "销售数量"); dataGridViewSales.Columns.Add("UnitPrice", "单价"); dataGridViewSales.Columns.Add("TotalAmount", "总金额"); // 将各控件添加到销售管理窗口 Controls.Add(dateTimePickerSalesDate); Controls.Add(comboBoxGoods); Controls.Add(textBoxQuantity); Controls.Add(textBoxUnitPrice); Controls.Add(textBoxTotalAmount); Controls.Add(buttonAddSales); Controls.Add(buttonViewSales); Controls.Add(dataGridViewSales); } private void LoadGoodsData() { goodsList = LoadGoods(); foreach (Goods good in goodsList) { comboBoxGoods.Items.Add(good.Name); } } private List<Goods> LoadGoods() { List<Goods> result = new List<Goods>(); string connectionString = "Data Source=LAPTOP-ODQTAPDG\\MSSQLSERVER01;Initial Catalog=SnacksInventoryDB;User ID=root;Password=123456"; using (SqlConnection connection = new SqlConnection(connectionString)) { string query = "SELECT Goods_id, Goods_name, Unit_price, Category FROM Goods"; SqlCommand command = new SqlCommand(query, connection); try { connection.Open(); SqlDataReader reader = command.ExecuteReader(); while (reader.Read()) { int id = (int)reader["Goods_id"]; string name = reader["Goods_name"].ToString(); decimal price = (decimal)reader["Unit_price"]; string category = reader["Category"].ToString(); result.Add(new Goods(id, name, price, category)); } reader.Close(); } catch (Exception ex) { MessageBox.Show("加载商品数据出错:" + ex.Message); } } return result; } private void buttonAddSales_Click(object sender, EventArgs e) { if (ValidateInput()) { int goodsId = GetSelectedGoodsId(); int quantity = Convert.ToInt32(textBoxQuantity.Text); decimal unitPrice = Convert.ToDecimal(textBoxUnitPrice.Text); decimal totalAmount = quantity * unitPrice; DateTime salesDate = dateTimePickerSalesDate.Value; string connectionString = "Data Source=LAPTOP-ODQTAPDG\\MSSQLSERVER01;Initial Catalog=SnacksInventoryDB;User ID=root;Password=123456"; using (SqlConnection connection = new SqlConnection(connectionString)) { string query = "INSERT INTO sales (sales_date, goods_id, quantity, total_amount) VALUES (@SalesDate, @GoodsId, @Quantity, @TotalAmount)"; SqlCommand command = new SqlCommand(query, connection); command.Parameters.AddWithValue("@SalesDate", salesDate); command.Parameters.AddWithValue("@GoodsId", goodsId); command.Parameters.AddWithValue("@Quantity", quantity); command.Parameters.AddWithValue("@TotalAmount", totalAmount); try { connection.Open(); command.ExecuteNonQuery(); MessageBox.Show("销售记录添加成功!"); ClearInputFields(); LoadSalesRecords(); } catch (Exception ex) { MessageBox.Show("添加销售记录出错:" + ex.Message); } } } } private bool ValidateInput() { if (string.IsNullOrEmpty(textBoxQuantity.Text)) { MessageBox.Show("请输入销售数量!"); return false; } if (string.IsNullOrEmpty(textBoxUnitPrice.Text)) { MessageBox.Show("请输入商品单价!"); return false; } if (!int.TryParse(textBoxQuantity.Text, out _)) { MessageBox.Show("销售数量必须为整数!"); return false; } if (!decimal.TryParse(textBoxUnitPrice.Text, out _)) { MessageBox.Show("商品单价格式不正确!"); return false; } return true; } private int GetSelectedGoodsId() { string selectedGoodsName = comboBoxGoods.SelectedItem.ToString(); foreach (Goods good in goodsList) { if (good.Name == selectedGoodsName) { return good.Id; } } return -1; } private void ClearInputFields() { textBoxQuantity.Text = ""; textBoxUnitPrice.Text = ""; textBoxTotalAmount.Text = ""; comboBoxGoods.SelectedIndex = -1; } private void buttonViewSales_Click(object sender, EventArgs e) { LoadSalesRecords(); } private void LoadSalesRecords() { dataGridViewSales.Rows.Clear(); string connectionString = "Data Source=LAPTOP-ODQTAPDG\\MSSQLSERVER01;Initial Catalog=SnacksInventoryDB;User ID=root;Password=123456"; using (SqlConnection connection = new SqlConnection(connectionString)) { string query = "SELECT s.sales_date, g.goods_name, s.quantity, g.unit_price, s.total_amount " + "FROM sales s " + "JOIN goods g ON s.goods_id = g.goods_id"; SqlCommand command = new SqlCommand(query, connection); try { connection.Open(); SqlDataReader reader = command.ExecuteReader(); while (reader.Read()) { DateTime salesDate = (DateTime)reader["sales_date"]; string goodsName = reader["goods_name"].ToString(); int quantity = (int)reader["quantity"]; decimal unitPrice = (decimal)reader["unit_price"]; decimal totalAmount = (decimal)reader["total_amount"]; dataGridViewSales.Rows.Add(salesDate, goodsName, quantity, unitPrice, totalAmount); } reader.Close(); } catch (Exception ex) { MessageBox.Show("加载销售记录出错:" + ex.Message); } } } private class Goods { public int Id { get; set; } public string Name { get; set; } public decimal Price { get; set; } public string Category { get; set; } public Goods(int id, string name, decimal price, string category) { Id = id; Name = name; Price = price; Category = category; } } private void FormSalesManagement_Load(object sender, EventArgs e) { // 加载商品列表数据,用于填充商品下拉框 LoadGoodsData(); // 设置销售日期选择器的初始值(示例,可根据需求调整,比如设置为最近一周开始日期等) dateTimePickerSalesDate.Value = DateTime.Today; // 可以设置页面中其他控件的初始状态,例如输入框的默认提示文本等 textBoxQuantity.Text = "请输入销售数量"; textBoxQuantity.ForeColor = Color.Gray; textBoxQuantity.GotFocus += (s, args) => { if (textBoxQuantity.Text == "请输入销售数量") { textBoxQuantity.Text = ""; textBoxQuantity.ForeColor = Color.Black; } }; textBoxQuantity.LostFocus += (s, args) => { if (string.IsNullOrEmpty(textBoxQuantity.Text)) { textBoxQuantity.Text = "请输入销售数量"; textBoxQuantity.ForeColor = Color.Gray; } }; // 还可以进行页面外观相关的设置,比如设置背景颜色等(以下是示例,可按需更改) this.BackColor = Color.WhiteSmoke; } private DateTimePicker dateTimePickerSalesDate; private ComboBox comboBoxGoods; private TextBox textBoxQuantity; private TextBox textBoxUnitPrice; private TextBox textBoxTotalAmount; private DataGridView dataGridViewSales; } }
namespace SnacksInventorySystem { partial class FormSalesManagement { /// <summary> /// 必需的设计器变量。 /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// 清理所有正在使用的资源。 /// </summary> /// <param name="disposing">如果应释放托管资源,为 true;否则为 false。 protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows 窗体设计器生成的代码 /// <summary> /// 设计器支持所需的方法 - 不要修改 /// 使用代码编辑器修改此方法的内容。 /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(600, 400); this.IsMdiContainer = false; this.MainMenuStrip = null; this.Name = "FormSalesManagement"; this.Text = "销售管理"; this.Load += new System.EventHandler(this.FormSalesManagement_Load); } #endregion } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 字符编码:从基础到乱码解决
· 提示词工程——AI应用必不可少的技术