C# Access Method of Form1 on Form2

后端 未结 4 964
生来不讨喜
生来不讨喜 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 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 with custom event argument, which will provide entered url to subscribers.

提交回复
热议问题