C#的winform商品信息管理程序

编写一个Windows应用程序,具体要求:

  1. 创建SqlServer数据库MyDb(使用集成身份验证方式访问数据库)

  2. 创建商品表"Products",Products表中的字段及类型如表1所示。建表成功后自行插入数据若干条。

  3. 创建一个"显示所有商品信息"窗体,如图1所示。窗体加载时即显示数据库表Products中所有数据。运行效果如图2所示。

表1 Products表字段说明

|-----------------|--------------|------|------|
| 字段名 | 数据类型 | 是否主键 | 含义 |
| ProductID | nvarchar(10) | 是 | 商品编号 |
| ProductName | nvarchar(30) | 否 | 商品名称 |
| ProductCategory | nvarchar(20) | 否 | 商品类别 |
| Price | numeric(7,2) | 否 | 商品单价 |

代码如下所示:

先在sql sever软件里创建表,如下图所示:

在vs软件里创建两个窗体,具体如下图:

代码如下:要连接数据库的字符串,如下:

private void Form1_Load(object sender, EventArgs e)

{

// 打开数据库连接

sqloperation.dbopen();

string sql = "select * from product";

// 绑定数据集到DataGridView控件

dataGridView1.DataSource = sqloperation.query(sql);

}

private void button2_Click(object sender, EventArgs e)

{

this.Close();

}

private void button1_Click(object sender, EventArgs e)

{

updateform addform = new updateform();

addform.ShowDialog();

this.Close();

}

添加窗体代码如下:

private void button1_Click(object sender, EventArgs e)

{

string id = textBox1.Text.Trim(); // 商品编号

string name = textBox2.Text.Trim();// 商品名称

string category = textBox3.Text.Trim();// 商品类别

string price = textBox4.Text.Trim();// 商品单价

string sql = $"insert into product values('{id}','{name}','{category}','{price}')";

update(sql);

this.Close();

Form1 info = new Form1();

info.ShowDialog();

}

//执行操作

public static string update(string sql)

{

try{

SqlConnection conn = new SqlConnection("Data Source=.;Initial Catalog=product;Integrated Security=True"); // 打开数据库连接

conn.Open();

SqlCommand cmd = new SqlCommand(sql, conn);

int result = cmd.ExecuteNonQuery();

conn.Close();

MessageBox.Show("商品添加成功");

return "success";

}

catch(Exception e)

{

MessageBox.Show(e.Message);

return e.ToString();

}

}

相关推荐
逸狼6 分钟前
【JavaEE进阶】Spring DI
java·开发语言
Ljw...14 分钟前
DeepSeek+Kimi生成高质量PPT
数据库·c++·powerpoint·ppt·deepseek
m0_7482405421 分钟前
数据库操作与数据管理——Rust 与 SQLite 的集成
数据库·rust·sqlite
生产队队长23 分钟前
ThinkPHP:配置Redis并使用
android·数据库·redis
my_styles35 分钟前
2025-alibaba-Sentinel组件
java·开发语言·sentinel
致奋斗的我们36 分钟前
HAProxy介绍与编译安装
linux·汇编·数据库·mysql·青少年编程·haproxy·openeurler
禁默1 小时前
C++之旅-C++11的深度剖析(1)
开发语言·c++
偏右右1 小时前
UNION 联合查询
数据库·sql
追烽少年x1 小时前
C# WinForm 中的事件驱动模型
c#
Mr-Apple1 小时前
MySQL的Union和OR查询
android·数据库·mysql