我有一个如下所示的form1:
和AddSnackForm,如下所示:
如何使用AddSnackForm添加零食并将其放入Form1的列表中?我尝试使用“using”语句,但它只是添加了一个默认值为Snack(“",0,0)的零食。
Form1的代码:
public partial class Form1 : Form
{
SnackBar snackBar;
public Form1()
{
snackBar = new SnackBar(new Snack("Chocolate", 2, 10),
new Snack("Soda", 1.5, 10),
new Snack("Chips", 3, 20));
InitializeComponent();
lbSnacks.Items.Clear();
foreach(Snack snack in snackBar.Snacks)
{
lbSnacks.Items.Add(snack);
}
}
private void BtnOrder_Click(object sender, EventArgs e)
{
double orderPrice = snackBar.ProcessOrder(int.Parse(cbSnackOne.Text), int.Parse(cbSnackTwo.Text), int.Parse(cbSnackThree.Text));
if (orderPrice > 0)
{
snackBar.Revenue += orderPrice;
MessageBox.Show($"Your order costs {orderPrice:f2}€.");
}
else
{
switch (orderPrice)
{
case -1:
MessageBox.Show("Snack One not in stock. Your order cannot be processed.");
break;
case -2:
MessageBox.Show("Snack Two not in stock. Your order cannot be processed.");
break;
case -3:
MessageBox.Show("Snack Three not in stock. Your order cannot be processed.");
break;
}
}
}
private void BtnAdd_Click(object sender, EventArgs e)
{
Snack snack = new Snack("", 0, 0);
using (AddSnackForm add = new AddSnackForm()) ;
add.Show();
snack = add.snack;
snackBar.Snacks.Add(snack);
lbSnacks.Items.Add(snack);
}
AddSnackForm的程式码:
public partial class AddSnackForm : Form
{
public Snack snack = new Snack("", 0, 0);
public AddSnackForm()
{
InitializeComponent();
}
private void BtnAdd_Click(object sender, EventArgs e)
{
snack.Name = tbName.Text;
snack.Price = double.Parse(tbPrice.Text);
snack.InStockAmount = int.Parse(tbAmount.Text);
Close();
}
}
1条答案
按热度按时间n53p2ov01#
根据我的经验,有两种不同的方法:
1.将列表框从form1传递到AddSnackForm作为引用:
表格1:
添加零食表单:
我想这是最简单的方法...
1.使用回调,这有点复杂,但在我看来是一个更干净的解决方案。