简体   繁体   English

从2种不同的方法调用表单

[英]calling a form from 2 different methods

I am am trying to access a form from a button which sends over data, and a menustrip button that just looks at the form, no data transferred. 我正在尝试通过发送数据的按钮和仅查看表单而不传输数据的菜单栏按钮访问表单。

to send the data over I have the class name being: 通过发送数据,我的类名为:

    public xSecForm(string dataRecieved)
    {
        InitializeComponent();

        xSavedList.Text = dataRecieved;
    }

this allows me to send data over on the first button. 这使我可以通过第一个按钮发送数据。

Ive seen other help saying to put 我看过其他帮助说要放

    xSecForm f2 = new xSecForm()
    f2.Show();

in the menu button to just show the window without data passing, but because of the (string dataRecieved) at the end of the form it keeps giving me errors. 在菜单按钮中仅显示不传递数据的窗口,但是由于表单末尾的(字符串dataRecieved)它不断给我带来错误。

I was hoping there may be a way to do it without changing how the data is being sent over. 我希望可以在不更改数据发送方式的情况下进行操作。

A couple of methods you can try, each have their benefits and drawbacks. 您可以尝试两种方法,每种方法都有其优点和缺点。

1) You can have 2 constructors for your second form. 1)第二种形式可以有2个构造函数。 One would be default (would not pass in data), and the other would allow you to pass in a string. 一个将是默认值(不会传递数据),另一个将允许您传递字符串。

public xSecForm(string dataReceived)
{
    InitializeComponent();
    xSavedList.Text = dataReceived;
}

public xSecForm()
{
    InitializeComponent();
}

This way you can make a new instance of the second form with or without sending the string in. The drawback is that you can only pass in data when you first create the object. 这样,您可以在发送或不发送字符串的情况下创建第二种形式的新实例。缺点是只能在首次创建对象时传递数据。

2) Make a public property in your second form to allow the first form to inject data in itself. 2)在第二种形式中设置一个公共财产,以允许第一种形式本身注入数据。 In your second form: 在第二种形式中:

public string SavedListData
{
    set { xSavedList.Text = value; }
    get { return xSavedList.Text; }
}

Then on your main form (assuming you have a default constructor) 然后在您的主窗体上(假设您具有默认构造函数)

xSecForm f2 = new xSecForm();
f2.SavedListData = "asdf";
f2.Show();

The benefit for this approach is that you can get/set the data whenever, even after you have loaded and have used the second form. 这种方法的好处是,即使加载并使用了第二种形式,您也可以随时获取/设置数据。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM