winform中添加的商品怎么在数据库中显示
时间: 2023-05-27 09:02:07 浏览: 78
您可以使用ADO.NET或Entity Framework等数据访问技术,将WinForm应用程序中的添加商品操作与数据库进行交互,将商品信息保存到数据库中。具体操作流程如下:
1. 创建数据库表,用于存储商品信息。
2. 在WinForm应用程序中,添加添加商品的功能,即在界面上提供商品信息的输入框和添加按钮等控件。
3. 在添加按钮的事件处理方法中,获取用户输入的商品信息,并通过数据库连接对象创建SqlCommand对象,将商品信息插入到数据库表中。
4. 在WinForm应用程序中添加查询商品的功能,即在界面上提供查询商品信息的输入框和查询按钮等控件。
5. 在查询按钮的事件处理方法中,获取用户输入的商品信息,使用SqlCommand对象查询数据库中的商品信息,并将查询结果显示在界面上。
以下是C#代码示例:
```
// 添加商品
private void btnAdd_Click(object sender, EventArgs e)
{
// 获取用户输入的商品信息
string name = txtName.Text;
decimal price = decimal.Parse(txtPrice.Text);
int inventory = int.Parse(txtInventory.Text);
// 将商品信息插入到数据库中
string connectionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password";
using(SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
SqlCommand command = new SqlCommand("INSERT INTO Product(Name, Price, Inventory) VALUES(@Name, @Price, @Inventory)", connection);
command.Parameters.AddWithValue("@Name", name);
command.Parameters.AddWithValue("@Price", price);
command.Parameters.AddWithValue("@Inventory", inventory);
command.ExecuteNonQuery();
}
}
// 查询商品
private void btnSearch_Click(object sender, EventArgs e)
{
// 获取用户输入的商品名称
string name = txtSearchName.Text;
// 查询数据库中的商品信息
string connectionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password";
using(SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
SqlCommand command = new SqlCommand("SELECT * FROM Product WHERE Name=@Name", connection);
command.Parameters.AddWithValue("@Name", name);
SqlDataReader reader = command.ExecuteReader();
while(reader.Read())
{
// 将查询结果显示在界面上
string productName = reader.GetString(1);
decimal productPrice = reader.GetDecimal(2);
int productInventory = reader.GetInt32(3);
// TODO: 在界面上显示商品信息
}
}
}
```