C# Access Method of Form1 on Form2

后端 未结 4 946
生来不讨喜
生来不讨喜 2021-01-16 21:42

I have 2 Forms in my project. Form1 is the main Form. There I have a button to open Form2, a ListView and a method to call a url and feed the ListView with data it gets from

相关标签:
4条回答
  • 2021-01-16 21:49

    Define a property on Form2 to allow the access of the result

    // In Form2
    public string Url { get { return urlTextBox.Text; } }
    

    In Form1

    var form2 = new Form2();
    form2.ShowDialog(this);
    string url = form2.Url;
    

    Note: unless Show() the ShowDialog() method waits until form2 is closed.

    The ShowDialog argument this is the owner of the form to be opened. It binds form2 to form1 and makes it always appear on top of form1.

    0 讨论(0)
  • 2021-01-16 21:58

    It creates a new instance because you are calling new.

    You can loop over Application.OpenForms and check form names. After finding Form1, you can easily call its public method;

    Form1(Application.OpenForms[0] as Form1).method();
    
    0 讨论(0)
  • 2021-01-16 22:00

    Have a look:

    //In Form1 opening Form2
    Form2 frm = new Form2();
    frm.Owner = this;
    frm.Show();
    
    //Example to call methods in FORM1 from FORM2
    private void button1_Click(object sender, EventArgs e)
    {
        Form1 frmParent = (Form1)this.Owner;
        frmParent.testeFunction();
        frmParent.InsertInGrid(textBox1.Text);
    }
    

    So, basically you need to create one function in Form1 to call from Form2 (passing Parameters). I hope this helps.

    0 讨论(0)
  • 2021-01-16 22:11

    Define event on Form2 and raise it when url entered:

    public class Form2 : Form
    {
       public event EventHandler UrlEntered;
    
       private void ButtonOK_Click(object sender, EventArgs e)
       {
           if (UrlEntered != null)
               UrlEntered(this, EventArgs.Empty);
       }
    
       public string Url { get { return urlTextBox.Text; } }
    }
    

    Subscribe to that event on Form1:

    Form2 form2 = new Form2()
    form2.UrlEntered += Form2_UrlEntered;
    form2.Show();
    

    Handle this event:

    private void Form2_UrlEntered(object sender, EventArgs e)
    {
       Form2 form2 = (Form2)sender;
       string url = form2.Url;
       // use it
    }
    

    Also you can define event of type EventHandler<UrlEnteredEventArgs> with custom event argument, which will provide entered url to subscribers.

    0 讨论(0)
提交回复
热议问题