Home > Mobile >  Display Label Text in different forms in Windows Forms
Display Label Text in different forms in Windows Forms

Time:09-06

I am making a fast food ordering app. My question is how can I display the label text which holds the price of a item such as pepperoni pizza , and display it in the cart which is on a different form. Any answers are welcomed.

CodePudding user response:

You want it hardcoded ? or you gonna work with a database like SQL or MySql? you have some options to do it.

You could store prices and items in a Database or work with a list/Array

List<Decimal> Prices = new List<Decimal>(); 
Prices.Add("12.50"); 

Not sure what you prefer at this moment.

let me know and then i will give you a better answer.

CodePudding user response:

This is were delegate/event works. In this example, the model is simple.

public class Product
{
    public string Name { get; set; }
    public decimal Price { get; set; }
    public int Quantity { get; set; }
}

Child form creates a mocked Product and in the Click event of a Button invokes with the mocked product.

public partial class Form2 : Form
{
    public delegate void OnAddProduct(Product product);
    public event OnAddProduct AddProduct;
    public Form2()
    {
        InitializeComponent();
    }

    private void AddProductButton_Click(object sender, EventArgs e)
    {
        AddProduct?.Invoke(new Product()
        {
            Name = "pepperoni pizza", 
            Price = 5.99m, 
            Quantity = 1
        });
    }
}

In the calling form, an instance of the child form is created and subscribes to OnAddProduct

public partial class Form1 : Form
{
    
    public Form1()
    {
        InitializeComponent();
    }

    private void OpenFormButton_Click(object sender, EventArgs e)
    {
        Form2 form2 = new Form2();

        try
        {
            form2.AddProduct  = OnAddProduct;
            form2.ShowDialog();
        }
        finally
        {
            form2.Dispose();
        }
    }

    private void OnAddProduct(Product product)
    {
        label1.Text = $"{product.Name} {product.Price:C} {product.Quantity}";
    }
}
  •  Tags:  
  • c#
  • Related