从另一种形式调用一个类

发布于 2025-01-02 06:13:04 字数 647 浏览 1 评论 0原文

我正在尝试从 C# 中的 form2 调用类,下面的示例是来自“Form2”的代码。

    private void button17_Click(object sender, EventArgs e)
     {

         Form1 frontmain = new Form1();
         frontmain.buttonchange();
         this.Hide();
     }

这不会执行“Form1”中名为“buttonchange”的类。下面是“buttonchange”类的代码:

    public void buttonchange()
    {
            button1.Text = workshop1;
            button2.Text = workshop2;
            button3.Text = workshop3;
            button4.Text = workshop4;
            button5.Text = workshop5;
    {

我认为它与 form1 和 form2 之间的隐私设置有关,但我从未找到解决方案。我总是以某种方式解决这个问题。有谁知道这里的问题是什么?

I am trying to call to class from form2 in C# for, example below is code from "Form2".

    private void button17_Click(object sender, EventArgs e)
     {

         Form1 frontmain = new Form1();
         frontmain.buttonchange();
         this.Hide();
     }

This will not excute the class in "Form1" called "buttonchange." Below is the code for the "buttonchange" class:

    public void buttonchange()
    {
            button1.Text = workshop1;
            button2.Text = workshop2;
            button3.Text = workshop3;
            button4.Text = workshop4;
            button5.Text = workshop5;
    {

I assume it has something to do with privacy settings between form1 and form2 however I have never found the solution. I have always worked around it somehow. Does anyone know what the issue is here?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

暮年 2025-01-09 06:13:04

我将在 form2 上设置事件并设置 form1 来捕获 form1 事件。

以下是设置事件的链接:

http://msdn.microsoft.com/ en-us/library/awbftdfh.aspx

I would set up events on form2 and set up form1 to capture the form1 events.

Here is a link to setting up events:

http://msdn.microsoft.com/en-us/library/awbftdfh.aspx

℉服软 2025-01-09 06:13:04

您正在创建 Form1 的新实例并在其上调用代码,这可能不是您真正想要做的。

如果您尝试引用 Form1 的现有实例,那么您需要引用该实例(而不是创建一个新实例)。

如果 Form1 的实例生成您的点击处理程序所在的表单,您可以像这样引用它:

Form1 frontmain = this.Owner as Form1;

如果 Form1 的实例没有生成您的第二个表单单击处理程序,那么您将需要采用基于事件的方法(无论如何,这是一个更好的方法,因为它消除了依赖性)。

You're creating a new instance of Form1 and calling code upon that, which is probably not what you actually intend to do.

If you're trying to refer to an existing instance of Form1, then you'll need to refer to that (rather than create a new instance).

If an instance of Form1 spawns the form that your click handler is in, you can refer to it like this:

Form1 frontmain = this.Owner as Form1;

If an instance of Form1 doesn't spawn your second form with the click handler, then you will need to take an event-based approach (which is a better approach anyway, as it eliminates dependencies).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文