c# - 从列表中获取数据到 datagridview
问题描述
我正在创建一个事件驱动的购物车,因此我让它显示在 datagridview 中,但它首先将信息存储在一个列表中,当我单击 Checkout 按钮时,它会从该列表中转到 datagridview .
然后发生的是生成了列和行,但随后它也显示了行,但数据不可见,只有行和列。
这就是现在的样子。
//defines the list and links to the where the product information is and when a product is added to the cart.
public static List<BulkPurchase> cart = new List<BulkPurchase>();
private void btnCheckout_Click(object sender, EventArgs e)
{
//makes the checkout visible
pnlMain.Visible = false;
//makes the products not visible
pnlCheckout.Visible = true;
//just shows me that items have been added to the list
foreach (var item in cart)
{
Console.WriteLine(item.getName());
Console.WriteLine(item.getPrice());
}
//inputs the cart to the datagridview
dataGridView1.DataSource = cart;
}
大宗采购类
public class BulkPurchase : Product
{
private int quantity;
public BulkPurchase(string prodName, float prodPrice, int prodQuantity)
: base(prodName, prodPrice)
{
this.quantity = prodQuantity;
}
}
产品类别
public class Product
{
private string name;
private float price;
//the constructor for a product
public Product (string prodName, float prodPrice)
{
this.name = prodName;
this.price = prodPrice;
}
//accessing the private variable of name
public string getName() => name;
//accessing the private variable of price
public float getPrice() => price;
}
当我将三个项目添加到列表中时,这是 datagridview 的结果
我完全不知道如何解决这个问题,所有的谷歌搜索和 YouTube 都没有帮助。
解决方案
我不确定这是否是您的意思。您需要做的第一件事是定义公共产品名称属性、公共价格属性和公共数量属性。属性是可读和可写的属性。这样,控件就可以访问类之外的那些私有字段。
我的修改如下:
//手动将示例直接添加到demo中的列表中
//Write three data as an example
cart.Add(new BulkPurchase("apple",10,1));
cart.Add(new BulkPurchase("banana", 20, 1));
cart.Add(new BulkPurchase("orange", 10, 1));
//产品
public class Product {
private string name;
private float price;
public string ProductName {
get {
return name;
}
set {
name = value;
}
}
public float Price {
get {
return price;
}
set {
price = value;
}
}
//批量购买
public class BulkPurchase : Product {
private int quantity;
public BulkPurchase(string prodName, float prodPrice, int prodQuantity)
: base(prodName, prodPrice) {
Quantity = prodQuantity;
}
public int Quantity {
get {
return quantity;
}
set {
quantity = value;
}
}
}
//显示总金额。
float TotalPrice = 0;
foreach (var item in cart) {
TotalPrice += (item.Price*item.Quantity);
}
pnlCheckout.Text = $"Total $ {TotalPrice}";
//将数量放在第三列。
dataGridView1.DataSource = cart;
dataGridView1.Columns[0].DisplayIndex = 2;
推荐阅读
- javascript - Flutter移动平台如何使用html、javascript代码?
- r - 绘制乘以因子 k 的拟合线性回归
- signal-processing - 具有实到实函数的逆离散傅里叶变换
- c# - ASP.NET MVC EF Core,视图中的属性访问,同时在不同模型的选定 ID 上
- google-maps - 如何在谷歌地图颤动中获取当前相机位置latlng
- android - 安卓wordpress自动fcm通知收不到
- javascript - JavaScript 动态加载脚本文件以创建一个对象,然后在该对象上运行 .init()
- wordpress - 自定义帖子类型的多个用户角色
- sql - 更改 SQL 中列的显示顺序
- next.js - Nextjs 和工作箱集成