0

In Form1 I have a textbox filled with char array values (*). Then in Form2 I change one of the array values (change * to some letter) and I have to update Form1 textbox. But when I press button - nothing happens. Form2 code snippet:

 private void button2_Click(object sender, EventArgs e)
        {
            .... 
            ....

            letter = (char)Form1.number;  
            textbox1.Text = letter.ToString(); //shows me the letter I'm replacing '*' with
        }


private void button3_Click(object sender, EventArgs e)
        {
            frm1 = new Form1();

            Form1.charArray[Convert.ToInt32(frm1.numericUpDown2.Value)] = letter; //which array value I'm changing

            frm1.textBox2.Text = String.Empty;

            for (int i = 0; i < frm1.numericUpDown1.Value; i++)
            {
                frm1.textBox2.Text += Form1.charArray[i];
            }
        }
Bat Man
  • 35
  • 3
  • You are not editing the `Form1`-instance that is visible to you. Instead, you **create** a new one here and change that (but never show it - which would result in two `Form1`-windows visible) – olydis Aug 30 '15 at 23:53
  • so I have to edit the line like **Form1**.textBox2.Text += Form1.charArray[i] ? – Bat Man Aug 31 '15 at 00:00
  • That probably would work if you declared `textBox2` static and assigned it the right value... read my answer for further options :) – olydis Aug 31 '15 at 00:08

1 Answers1

1

Instead of editing the Form1-window you are talking about, you are creating a new (yet invisible) one in your event-handler and perform your operations on that.

Solution:

As you are already doing with some fields (charArray, number), you have to give this method "access" to the very instance of Form1 that already exists!

Option 1: As you have done with the charArray and number, add a static field to Form1 (something like public static Form1 instance;), and assign to it the correct instance. For example, put Form1.instance = this; inside of Form1's constructor.

Option 2: Wherever you are creating and showing your Form2-window (I guess there is something like new Form2().Show() in your code and I bet it has access to your instance of Form1 - maybe you even do this from within Form1), you could pass the right instance of Form1 as a constructor argument, i.e. you change Form2's constructor so it accepts a parameter of type Form1 and then call new Form2(theRightInstanceOfForm1).

Summary: Although "Option 2" is definitely the cleaner one, I guess it will give you more trouble than "Option 1": Not only did you already define several static fields (so it would not really make a difference to add another one), if you are using the Visual Studio Designer to design Form2, it will break as soon as you change its constructor...

olydis
  • 3,192
  • 13
  • 28
  • 1
    I would avoid option 1 if possible - `static` fields will cause you more trouble in the long run. Option 2 is the way to go, IMHO. – Enigmativity Aug 31 '15 at 00:17