我觉得我在这里错过了一些明显的东西。 This is a screenshot of my form.如何使用另一个类中的方法添加到ListBox?
我有两个类ShoppingBasket和OrderItem,然后Form1类。 OrderItem中有四个属性,我想在ShoppingBasket中使用。我想在textbox1中获取产品名称,numericupdown1中的数量和textbox2中的最新价格,然后单击添加按钮,该按钮将使用OrderItem类验证值,然后将它们放入ShoppingBasket类的AddProduct方法中这将有望在表单中向列表框中添加一行。
Form1中:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void addButton_Click(object sender, EventArgs e)
{
decimal latestPrice;
ShoppingBasket addButtonShoppingBasket = new ShoppingBasket();
decimal.TryParse(textBox2.Text, out latestPrice);
OrderItem currentItemQuantity1 = new OrderItem(textBox1.Text, latestPrice, Convert.ToInt32(numericUpDown1.Value));
addButtonShoppingBasket.AddProduct(currentItemQuantity1.ProductName, currentItemQuantity1.LatestPrice, currentItemQuantity1.Quantity);
}
}
ShoppingBasket:
public class ShoppingBasket
{
public ShoppingBasket()
{
}
public void AddProduct(string productName, decimal latestProductValue, int quantity)
{
Form1 newform = new Form1();
string itemFormatString = "{0,-50}{1,0}{2,50}";
newform.listBox1.Items.Add(string.Format(itemFormatString, productName, Convert.ToString(quantity), Convert.ToString(latestProductValue)));
}
}
OrderItem的:
public class OrderItem
{
public OrderItem(string productName, decimal latestPrice, int quantity)
{
ProductName = productName;
LatestPrice = latestPrice;
Quantity = quantity;
TotalOrder = latestPrice * quantity;
}
public string ProductName { get; set; }
public decimal LatestPrice { get; set; }
public int Quantity { get; set; }
public decimal TotalOrder { get; set; }
}
你有什么问题? – PoweredByOrange
为什么不直接返回字符串并添加到表单中,而不是在方法中添加?你的方法不一定是'void'。 – SimpleVar
@PoweredByOrange - 它说'listBox1由于其保护级别而无法访问',所以我认为我没有这样做。任何想法? –