在C#中两个实例化的WinForms之间传递数据

时间:2013-02-09 12:17:52

标签: c# .net winforms

我有一个主表单,它可以显示计算并打开和关闭用户创建的项目。

当用户点击File下的Open Project按钮时,会打开一个名为Open Project的表单,如下所示,允许用户加载项目:

enter image description here

现在,我希望在单击“确定”后将此表单中的数据传递到主窗体中。

我遇到的问题是主表格已经打开。

对此问题的任何解决方案都会非常感激。

3 个答案:

答案 0 :(得分:1)

尝试在Properties

中创建Open Project Form

主要表格

private void openButton_Click(object sender, EventArgs e)
{
    using(var f = new Open_Project_Form())
    {
      f.ProjectReference = projectRefrencetTextBox.Text;
      f.ProjectNo = projectNoTextBox.Text;
      f.ShowDialog();
    }
}

打开项目表单

public string ProjectReference { get; set; }
public string ProjectNo { get; set; }

private void Open_Project_Form_Load(object sender, EventArgs e)
{
    projectRefrenceComboBox.Text = ProjectReference;
    projectNoTextBox.Text = ProjectReference;
}

更新

我误解了这个问题。我之前的回答是从MainFormOpenProjectForm,这次是从OpenProjectFormMainForm

主要表格

//Properties for MainForm
public string ProjectReference { get; set; }
public string ProjectNo { get; set; }

private void openButton_Click(object sender, EventArgs e)
{
    using(var f = new Open_Project_Form() { Owner = this })
    {
        f.ShowDialog();
        if (f.DialogResult == DialogResult.OK)
        {
          projectRefrencetTextBox.Text = ProjectReference;
          projectNoTextBox.Text = ProjectNo;
        }
    }
}

打开项目表单:请注意您有okButtoncancelButton

private void Open_Project_Form_Load(object sender, EventArgs e)
{
    okButton.DialogResult = DialogResult.OK;
    this.AcceptButton = okButton;
    this.CancelButton = cancelButton;
}

现在,在okButton_Click event

private void okButton_Click(object sender, EventArgs e)
{
   var f = Owner as MainForm;
   if (f == null) return;
   f.ProjectReference = projectRefrenceComboBox.Text;
   f.ProjectNo = projectNoTextBox.Text;
   Close();
}

参考:

希望它会对你有所帮助。

答案 1 :(得分:0)

你能使用活动吗?创建一个EventClass并将该值作为事件的结果返回。

答案 2 :(得分:0)

在已打开的表单类中创建一个事件:

public event EventHandler<ProjectDetailsArgs> ProjectDetailsSubmitted;
    public class ProjectDetails: EventArgs
    {
        public string projectReference{ get; set; }
        public string projectNo{get;set;}
        //you can add more prop.s here
    }

On your Ok button click event add 

if (ProjectDetailsSubmitted != null)
                {
                    ProjectDetailsArgs argss = new ProjectDetailsArgs();
                    argss.projectReference = projectRefrencetTextBox.Text;
                    argss.projectNo = projectNoTextBox.Text;
                    ProjectDetailsSubmitted(null, argss);
                }

在主窗体中为它创建一个处理程序:

  childform.ProjectDetailsSubmitted+=new EventHandler<ProjectDetailsArgs>project_detailsSubmitted);

                public void project_detailsSubmitted(object sender, ProjectDetailsArgs e)
                {
         //Do Your work
                }