从WinForm派生类返回自定义类对象

时间:2013-10-29 06:14:14

标签: c# .net winforms

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

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返回?

2 个答案:

答案 0 :(得分: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...语法确保表单在您完成后正确处理。

答案 1 :(得分:0)

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

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;
}