locked
use a variable from a form to another form RRS feed

  • Question

  • first form a have:

    public partial class Form4 : Form
        {------ 

    public int x4=0;
            private void button1_Click(object sender, EventArgs e)
            {

             x4=67;

             }

    ----}

    next form:

    i declare in the class:

    private Form4 frm4;

     private void button1_Click(object sender, EventArgs e)
            {

    frm4 = new Form4();

    DrawText(frm4.x4);

    //but it will show me 0, not 67... why? 


    Monday, February 2, 2015 11:00 AM

Answers

  • Because you are creating new instance of Form in "next form". You have to use the already opened insance. You could get a reference to it using the Application.OpenForms collection:


     private void button1_Click(object sender, EventArgs e)
             {
    
    Form4 frm4 = Application.OpenForms.OfType<Form4>().FirstOrDefault();
    
    DrawText(frm4.x4);
    

    Please remember to close your threads by marking helpful posts as answer.

    • Marked as answer by Raducu George Monday, February 2, 2015 11:40 AM
    Monday, February 2, 2015 11:08 AM

All replies

  • the value of x4 variable only changes when you click the button1 on form4. 

    For that reason the value is 0 not 67.

    You need to call a function from form4.

    A methd like this maybe:

    public partial class Form4 : Form
        {

    public int x4=0;

    public void SetIntValue()

    {

    x4 = 67;

    }

    }

    and in the other from just call this method as:

    frm4 = new Form4();

    frm4.SetIntValue();

    DrawText(frm4.x4);

    Monday, February 2, 2015 11:05 AM
  • Because you are creating new instance of Form in "next form". You have to use the already opened insance. You could get a reference to it using the Application.OpenForms collection:


     private void button1_Click(object sender, EventArgs e)
             {
    
    Form4 frm4 = Application.OpenForms.OfType<Form4>().FirstOrDefault();
    
    DrawText(frm4.x4);
    

    Please remember to close your threads by marking helpful posts as answer.

    • Marked as answer by Raducu George Monday, February 2, 2015 11:40 AM
    Monday, February 2, 2015 11:08 AM
  • it works now, thanks
    Monday, February 2, 2015 11:31 AM