这里的超级初学者。
我正在尝试在Windows Form C#中创建购物车功能
我有一个名为Shopping_Cart
datagridview的表格cartlist
。
并且我有一个单独的表单,其中包含我的产品Meat
,其中包含一个按钮,该按钮可添加到每个产品下方的购物车中,并带有BeefQty
数量文本框。
顺便说一句,通过侧面板上的按钮打开Shopping_Cart
和和Meat
页面,并在窗口的指定空间中将它们带到前面,因此我的应用程序基本上在单个窗口中运行。
我想做的是,当我单击添加按钮时,它将cartlist
以另一种形式添加行,而无需Shopping_Cart
在新窗口中打开。
到目前为止,我搜索过的所有解决方案都包括打开另一个我不想做的按钮单击形式的实例。
我尝试过的。
在Meat
形式
private void AddBeefBtn_Click(object sender, EventArgs e)
{
cartlist.ColumnCount = 3;
cartlist.Columns[0].Name = "Item";
cartlist.Columns[1].Name = "Quantity";
cartlist.Columns[2].Name = "Price";
string[] row = new string[] { "Beef", "BeefQty.text", "10*BeefQty.text" };
cartlist.Rows.Add(row);
}
它给了我一个错误,说CS0103 : The name 'cartlist' does not exist in the current context
我不明白,因为购物车列表确实存在于Shopping_Cart
表格中。
请注意,我对C#和Windows Form的使用绝对是零经验,并且我现在不太关心OOP概念,而我只是希望该应用程序能够正常运行。
请帮忙。
根据您的信息,收到邮件的原因CS0103 : The name 'cartlist' does not exist in the current
是由于中cartlist
存在Shopping_Cart
但不存在Meat
。他们不共享cartlist
,因此错误。
解决此问题的最简单方法是BindingList
在共享类中创建,然后将此列表绑定到cartlist
数据源。
给定
using System.ComponentModel;
using System.Runtime.CompilerServices;
namespace Test
{
// Model to use to fill the rows of the DataGridView
public class ItemModel : INotifyPropertyChanged
{
private string item;
private decimal qty, price;
public string Item
{
get => item;
set { item = value; OnPropertyChanged(); }
}
public decimal Quantity
{
get => qty;
set { qty = value; OnPropertyChanged(); }
}
public decimal Price
{
get => price;
set { price = value; OnPropertyChanged(); }
}
public event PropertyChangedEventHandler PropertyChanged;
// This is to notify the grid if any of the properties are updated
private void OnPropertyChanged([CallerMemberName] string name = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
}
}
}
我们可以创建一个共享类来存储BindingList
:
using System.ComponentModel;
namespace Test
{
public static class SharedData
{
public static BindingList<ItemModel> Items { get; set; } = new BindingList<ItemModel>();
}
}
从这里,我们将使用如下形式设置表单DataGridView
:
using System;
using System.Windows.Forms;
namespace Test
{
public partial class ShoppingCart : Form
{
public ShoppingCart()
{
InitializeComponent();
// Note how we are calling SharedData here
ItemDataGridView.DataSource = SharedData.Items;
}
}
}
我们可以添加BindingList
如下内容:
using System;
using System.Windows.Forms;
namespace Test
{
public partial class Meat : Form
{
public Meat()
{
InitializeComponent();
}
private void AddBeefBtn_Click(object sender, EventArgs e)
{
ItemModel model = new ItemModel
{
Item = "Beef",
Quantity = 10M,
Price = 9.95M,
};
SharedData.Items.Add(model);
}
}
}
输出量
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句