0

说,如果我有自己的数据类定义如下:

public class MyData
{
    public string v1;
    public int v2;
    //etc.
}

我可以将它传递给我自己的 Form 派生类并使用它来初始化表单控件:

public partial class MyForm : Form
{
    private MyData dataIn;

    public MyForm(MyData data)
    {
        InitializeComponent();

        dataIn = data;
    }
}

private void MyForm_Load(object sender, EventArgs e)
{
    //Init controls in 'MyForm' from 'dataIn'
}

private void buttonSave_Click(object sender, EventArgs e)
{
    //Save button was clicked

    //Read data from 'MyForm', but
    //how to return it back in 'MyData' class?

    //Close form
    this.DialogResult = System.Windows.Forms.DialogResult.OK;
    this.Close();
}

表单本身就是这样调用的:

//Initial data for the form
MyData data = new MyData(){
    v1 = "test",
    v2 = 123
};

MyForm dlg = new MyForm(data);
if (dlg.ShowDialog() == DialogResult.OK)
{
    //User clicked Save -- how to get data back in 'MyData'?
}

问题是如何让我MyData的数据填充并从中返回MyForm

4

2 回答 2

1

您应该提供一种在表单外访问结果数据的方法,可以是您可以读取的属性,也可以是您可以从其他地方调用的方法:

public partial class MyForm : Form
{
    private MyData dataIn;
    // Option 1: property that can be read from another class
    public MyData result { get; private set; }

    // Option 2: method you can call to get the result object
    public MyData GetResult()
    {
        return result;
    }

    public MyForm(MyData data)
    {
        InitializeComponent();

        dataIn = data;
    }

    private void buttonSave_Click(object sender, EventArgs e)
    {
        // set result object
        result = new MyData { v1 = "some string value", v2 = 123 }

        this.DialogResult = System.Windows.Forms.DialogResult.OK;
        this.Close();
    }
}

然后你的调用者会做类似的事情:

MyData dlgResult = null;
using (MyForm dlg = new MyForm(data))
{
    if (dlg.ShowDialog() == DialogResult.OK)
        dlgResult = dlg.GetResult();
}
if (dlgResult != null)
{
    // do something with the result
    //....
}

请注意,Form.Close()不处理表单。在处理它之前您仍然可以对其执行操作。语法确保表单在using (MyForm...完成后正确处理。

于 2013-10-29T06:23:21.720 回答
0

MyData在 MyForm 中创建类型的属性:

public partial class MyForm : Form
{
    private MyData dataIn;
    public MyData dataOut {get; set;}

    public MyForm(MyData data)
    {
        InitializeComponent();

        dataIn = data;
        dataOut = new MyData { v1 = "hi!", v2 = 2013 }; 
    }
}

然后你可以阅读它:

MyForm dlg = new MyForm(data);
if (dlg.ShowDialog() == DialogResult.OK)
{
    MyData dataFromForm = dlg.dataOut;
}
于 2013-10-29T06:22:56.743 回答