Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How Can I Set Dictionary Value On Other Form?

Tags:

c#

winforms

I am a C# beginner, I've encountered a problem as below, but I'm not sure what is causing it or how to fix it. Experience coders, please help.

I have a Dictionary in Form1, but I want to set its value from Form2. However, after assigning the value, the MessageBox result still shows 0;

Form1: msgbox show result = 0

    public Form1()
    {
        InitializeComponent();
        bidcoords["TEST"] = 0;
    }

    public Dictionary<string, int> bidcoords = new Dictionary<string, int>();

    private void button2_Click(object sender, EventArgs e)
    {
        MessageBox.Show(bidcoords["TEST"].Value.ToString());
    }

Form2:

    Form1 form1 = new Form1();

    private void button2_Click(object sender, EventArgs e)
    {
       form1.bidcoords["TEST"] = 30; 
    }
like image 260
Kelly Avatar asked Feb 25 '23 01:02

Kelly


2 Answers

Form1 form1 = new Form1();

Your are creating brand new object of Form1. Instead of this you need to pass existing instance of form1 to from2. But I advice you to pass only dictionary object instead of form

public class Form2 : Form
{
    public Dictionary<string, int> Bidcoords {get; set;}

    private void button2_Click(object sender, EventArgs e)
    {
        if(Bidcoords != null && Bidcoords.ContainsKey("TEST"))
           Bidcoords["TEST"] = 30;
    }
}

public class Form1: Form
{
    public void ShowForm2()
    {
        Form2 form = new Form2{Bidcoords = bidcoords ;}
        form.ShowDialog();
        MessageBox.Show(bidcoords["TEST"].Value.ToString());
    }
}
like image 95
Stecya Avatar answered Feb 26 '23 14:02

Stecya


At some point in your program you are creating Form2 and showing it. At that point in time you are in Form1. That Form1, the same one you can see on the screen, is the form you are trying to update. If you try to create another Form1 using new, all you will have is two Form1 instances, which is not what you want.

You need to communicate between Form1 and Form2 that instance of Form1.

There are two common approaches to doing this:

  1. Add a property called MainForm to Form2. After you create Form2, set form2.MainForm = this;
  2. Add a constructor to Form2 that takes a Form as an argument and save that away

In either case, then when you are in Form2, use that variable to set the dictionary.

like image 26
Rick Sladkey Avatar answered Feb 26 '23 15:02

Rick Sladkey