在Form2 Form1的C#存取方法 [英] C# Access Method of Form1 on Form2
问题描述
我在我的项目2个形式。
Form1中是主要形式。在那里,我有一个按钮,打开窗体2,一个ListView和调用一个网址,并用它从URL中获取数据养活ListView控件的方法。
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 the url.
窗体2有一个文本框URL和一个OK按钮。
Form2 has a textbox for the url and a button "Ok".
当我按在Form1上的按钮,它会打开Form2的,没有问题。
我如何管理它的URL传递到Form1的方法,如果我输入一个URL到窗体2的文本框,然后按OK?
When I press the button on Form1, it opens Form2, no problem. How can I manage it to pass the url to the method in Form1 if I enter a url into the textbox of Form2 and press Ok?
如果我这样做
Form1 form1 = new Form1();
form1.method();
这显然会打开Form1的新实例,执行的方法有,并填写列表框那里,但不在我原来的Form1上。
it will obviously open a new instance of Form1, execute the method there and fill the listbox there but not on my original Form1.
我发现问题的各种解决方案在线,但他们要么过于复杂或他们没有工作。
I found various solutions to the problem online but either they were too complicated or they didn't work.
我怎样才能把它,它实际上执行,我已经有,所以与值加载正确的列表框在Form1的方法?
How can I put it that it actually executes the method on the Form1 that I already have and therefore load the correct listbox with the values?
很多谢谢
推荐答案
在 Form2的定义事件
,并提高它时,输入的网址:
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; } }
}
订阅Form1上该事件:
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
}
您也可以定义类型的事件事件处理程序和LT; UrlEnteredEventArgs方式>
自定义事件参数,这将提供输入的URL给用户
Also you can define event of type EventHandler<UrlEnteredEventArgs>
with custom event argument, which will provide entered url to subscribers.
这篇关于在Form2 Form1的C#存取方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!