Windows Forms中DataGridView无法显示新增数据的问题求助
Windows Forms中DataGridView无法显示新增数据的问题求助
我现在用的是最新版本的VS和.NET SDK。
UPDATE:这是课程作业,要求不能用SQL数据库,只需要绑定数据就行。
我已经卡了好几周了,也查过其他相关问题,有的帮我修正了添加函数的写法,但还是没解决问题,有的情况和我的设置完全不一样。
我的主界面上有一个DataGridView,还有一个产品表单窗口,用户可以在这个表单里输入产品信息,点击保存后应该能在主界面的DataGridView里新增一行数据。调试的时候能看到所有值都传过去了,但就是不知道为什么DataGridView里不显示新增的行。
Main.Designer.cs 代码
private void InitializeComponent() { productGridView = new DataGridView(); productBindingSource = new BindingSource(components); productBindingSource.DataSource = typeof(Product); productGridView.DataSource = productBindingSource; } public DataGridView productGridView; public BindingSource productBindingSource; public void AddRows(int id, string name, float price, int instock, int min, int max) { this.productBindingSource.Add(new Product { ProductId = id, ProductName = name, ProductPrice = price, InStock = instock, Max = max, Min = min }); this.productGridView.Refresh(); }
产品表单中的Save_Click方法
public void Save_Click(object sender, EventArgs e) { int _id = Convert.ToInt32(Id.Text); string _name = ProductName.Text; float _price = float.Parse(ProductPrice.Text); int _qty = Convert.ToInt32(InStock.Text); int _min = Convert.ToInt32(Min.Text); int _max = Convert.ToInt32(Max.Text); Main _main = new(); _main.AddRows(_id, _name, _price, _qty, _min, _max); Close(); }
Product.cs 类代码
public class Product { public int ProductId { get; set; } public string? ProductName { get; set; } public double ProductPrice { get; set; } public int InStock { get; set; } public int Min { get; set; } public int Max { get; set; } }

备注:内容来源于stack exchange,提问作者Jamie Garcia
相关产品推荐
相关产品推荐

