我在usercontrol schuler中有listviewupdate()方法。用户控件schuler在form1中。然后我有了form2。当我在form2中单击一个按钮时,我想调用方法listviewupdate()。
我尝试在form1中创建第二个方法,该方法调用listviewupdate()方法,然后在Form2中调用第二个方法,但得到一个错误。有人能帮帮我吗?
发布于 2019-06-03 19:05:32
在文件Program.cs
中,您可以定义一个全局可访问的变量:
static class Program
{
// for external access to Form1 methods
public static Form1 MainForm;
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main(string[] args)
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
MainForm = new Form1(args);
Application.Run(MainForm);
}
}
然后,可以使用静态变量MainForm
通过Program.MainForm.MyMethod()
访问Form1
的任何公共方法。
假设您可以从Form1
中访问Form2
对象,则可以使用Form2
对象变量在Form1
方法之外调用Form2
方法。
请注意,在以下情况下您可能会遇到问题(不知不觉中...)使用多个线程。阅读有关BeginInvoke的信息。
发布于 2019-06-04 03:03:44
@Axel Kemper感谢您的回复。我用Program.MainForm.MyMethod()
按照你告诉我的做了,但是它没有找到MyMethod()。然后我进入form1.Designer,在那里我看到用户控件被设置为私有,我还将其切换为公共,现在它可以与Program.MainForm.schuler1.MyMethod() //schuler1 is the name of my user control
一起工作。
我就是不明白为什么它不能
Form1 form1 = Application.OpenForms[1] as Form1; form1.schuler1.ListviewUpdate(); //schuler1 is the name of my usercontrol
即使用户控件设置为public,我在main.schuler1.ListviewUpdate();
中也会收到错误“System.NullReferenceException
https://stackoverflow.com/questions/56425013
复制相似问题