Revo
Revo

Reputation: 5

how do i link listboxes throughout different forms

`I would like to Link Listboxes from one form to different other forms. For example if i were to add an item from another form that selected item will be shown throughout my other forms. is there any way to do this?

 private void pb_hd1_Click(object sender, EventArgs e)
 {

        int index = hm_drinks.FindIndex(drinks => drinks.Name.Equals(hd1.Text));
        pendinglist.Items.Add("1 \t" + hm_drinks[index].Name.PadLeft(20) + hm_drinks[index].Price.ToString("C").PadLeft(70));
        order.Equals(pendinglist.Items);
        total += hm_drinks[index].Price;
 }

This is what adds the item to the list box but the item is only shown in this form's list box. I would like it to be shown in other forms to which is my problem at the moment.

Upvotes: 1

Views: 138

Answers (1)

TrueEddie
TrueEddie

Reputation: 2233

You could store it in a variable of a singleton object and read that value from form to form.

Example Below

Singleton Class:

public class MySingletonClass
{
    private static MySingletonClass _instance;        

    /// <summary>
    /// Get the singleton instance.
    /// </summary>
    public static MySingletonClass Instance
    {
        get
        {
            if (_instance == null)
            {
                _instance = new MySingletonClass();
            }

            return _instance;
        }
    }

    /// <summary>
    /// Property to be shared across application.
    /// </summary>
    public string MySharedProperty { get; set; }

    // Private default constructor
    private MySingletonClass() { }
}

Form 1 which has a text box and then a button to open form 2. The button click event saves the textbox value to the singleton.:

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

    private void _openFormTwoButton_Click(object sender, EventArgs e)
    {
        MySingletonClass.Instance.MySharedProperty = textBox1.Text;

        Form2 form2 = new Form2();
        form2.Show();
    }
}

Form 2 which has a textbox. It loads the value from the singleton instance:

public partial class Form2 : Form
{
    public Form2()
    {
        InitializeComponent();

        textBox1.Text = MySingletonClass.Instance.MySharedProperty;
    }
}

Upvotes: 1

Related Questions