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;
}
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());
}
}
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:
MainForm
to Form2
. After you create Form2
, set form2.MainForm = this;
Form2
that takes a Form
as an argument and save that awayIn either case, then when you are in Form2
, use that variable to set the dictionary.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With