我认为问题是您comboBox3
在更新数据库中的剩余计数后不更新。
顺便说一句,您为什么为此使用组合框?数据库中的列名也非常混乱:Buy、GoodsNumber 和 Remain。很难猜测那里存储了哪些数据。考虑诸如 ProductId、Name 和 Quantity 之类的名称。
如果我要实现类似的东西,我会从将产品加载到组合框开始:
private void Form_Load(object sender, EventArgs e)
{
productsComboBox.DataSource = GetAllProducts();
productsComboBox.DisplayMember = "Name";
productsComboBox.ValueMember = "Id";
}
private IList<Product> GetAllProducts()
{
List<Product> products = new List<Product>();
// I use ConfigurationManager from System.Configuration.dll
// to read connection strings from App.config
string connectionString = ConfigurationManager.ConnectionStrings["anbar"].ConnectionString;
using (SqlConnection conn = new SqlConnection(connectionString))
{
string query = "SELECT * FROM Products";
SqlCommand cmd = new SqlCommand(query, conn);
conn.Open();
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
products.Add(new Product() { Id = (int)reader["Id"],
Name = (string)reader["Name"],
Quantity = (int)reader["Quantity"] });
}
}
return products;
}
产品简单类:
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public int Quantity { get; set; }
}
当所选产品发生变化时,显示其详细信息:
private void ProductsComboBox_SelectedIndexChanged(object sender, EventArgs e)
{
Product product = productsComboBox.SelectedItem as Product;
qtyTextBox.Text = product.Quantity.ToString();
// I use NumericUpDown control to input numbers
// Minimum is set to 1
qtyToSellNumericUpDown.Maximum = product.Quantity;
}
最后 - 当我输入要出售的数量(1..当前数量)时,我执行以下操作:
private void ButtonSell_Click(object sender, EventArgs e)
{
Product product = productsComboBox.SelectedItem as Product;
int qtyToSell = (int)qtyToSellNumericUpDown.Value;
SellProduct(product, qtyToSell);
product.Quantity -= qtyToSell; // update product
qtyTextBox.Text = product.Quantity.ToString(); // update current quantity
}
private void SellProduct(Product product, int qtyToSell)
{
string connectionString = ConfigurationManager.ConnectionStrings["anbar"].ConnectionString;
using (SqlConnection conn = new SqlConnection(connectionString))
{
string query = "UPDATE Products SET Quantity = @Quantity WHERE Id = @Id";
SqlCommand cmd = new SqlCommand(query, conn);
cmd.Parameters.AddWithValue("@Id", product.Id);
cmd.Parameters.AddWithValue("@Quantity", product.Quantity - qtyToSell);
conn.Open();
cmd.ExecuteNonQuery();
}
}
而已。是的,有很多需要改进的地方,但是这个小示例很有效。
更新:如何将连接字符串添加到 App.Config
<configuration>
<connectionStrings>
<add name="anbar"
connectionString="Data Source=PC-PC\PC;Initial Catalog=Anbar;Integrated Security=True"
providerName="System.Data.SqlClient"/>
</connectionStrings>
</configuration>