的WinForms之间传递变量 [英] Passing variable between winforms

查看:222
本文介绍了的WinForms之间传递变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Windows.Forms的应用程序就代表有问题。

I have a problem concerning delegates in a Windows.Forms application.

有两种形式:

  1. 的主要形式,其中有一个名为设置按钮。

  1. the main form, which has a button named "Settings".

设置的形式,这是孩子的形式。

the "settings" form, this is the "child" form.

当我点击主窗体的设置按钮,打开设置窗体的实例。

When I click the "Settings" button in the main form, it opens an instance of the Settings form.

我的问题是,我需要一个变量传递给设置形式,当我打开它。因此,新的形式将显示可变文本。我不知道如何来检索子设置形式的信息。我这样做一个教程在线下,不能从本教程了解如何阅读的目标形式的信息。

My problem is that I need to pass a variable to the Settings form, when I open it. So that the new form will show the variable text. I don't know how to retrieve the information in the child "Settings" form. I did this by following a tutorial online and could not understand from the tutorial how to read the info in the destination form.

下面是我做了什么,到目前为止,code的主要形式有:

Here's what I've done so far, the code in the main form:

public partial class MainForm : Form
{

    /// <summary>
    /// delegate to send data between forms
    /// </summary>
    public delegate void PageInfoHandler(object sender, PageInfoEventArgs e);
    /// <summary>
    /// event of the delegate
    /// </summary>
    public event PageInfoHandler PageInfoRetrieved;


    //other stuff, events blabla

    private void toolStripBtnSettings_Click(object sender, EventArgs e)
    {
        PageInfoEventArgs args = new PageInfoEventArgs(SomeString);
        this.OnPageInfoRetrieved(args);

        SettingsForm settingsForm = new SettingsForm();
        settingsForm.ShowDialog();  
    }

    private void OnPageInfoRetrieved(PageInfoEventArgs args)
    {
        if (PageInfoRetrieved != null)
            PageInfoRetrieved(this, args);
    }
}

感谢你的任何想法。

最好的问候,

/安德烈·

推荐答案

传递任何信息,你要到的设置形式的构造函数,并提供存取方法,你需要离开那里的东西。

Pass any information you want to in to the constructor of Settings form, and provide accessor methods for things you need out of there.

public class SettingsForm : WinForm
{
    private string m_Data;
    private int m_nExample = 0;

    // ctor
    public SettingsForm(string _data)
    {
        m_Data = data;  // you can now use this in SettingsForm
    } // eo ctor

    public int Example {get{return(m_nExample);} }
} // eo class SettingsForm

在上面的榜样,你可以构造一个SettingForm一个字符串,并获得在一个整数它可以使用。在您的code:

In the above "example" you can construct a SettingForm with a string and get at an integer it may use. In your code:

private void toolStripBtnSettings_Click(object sender, EventArgs e)
{
    PageInfoEventArgs args = new PageInfoEventArgs(SomeString);
    this.OnPageInfoRetrieved(args);

    SettingsForm settingsForm = new SettingsForm("some data to pass");
    settingsForm.ShowDialog();  

    int result = settingsForm.Example; // retrieve integer that SettingsForm used
}

这篇关于的WinForms之间传递变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆