【问题标题】:passing to a form which is already open传递给已经打开的表单
【发布时间】:2011-04-07 13:01:39
【问题描述】:

我正在尝试从数据库中加载一些信息。

为此,我打开了一个表单,其中列出了可以加载的所有内容。

当您单击加载时,我想将 ID 传递回原始表单。

但是我似乎无法以这种形式调用方法。

任何帮助将不胜感激。

【问题讨论】:

  • 你能告诉我们你试图在表单上调用方法的代码吗?

标签: c# .net winforms forms


【解决方案1】:

我会翻转这个:

  1. 将选择表单变成一个模式对话框,由您要加载内容的表单创建和显示
  2. 通过对话框表单中的属性或方法显示在对话框中所做的选择

通过这种方式,选择表单将与调用者分离,并且可以在任何有意义的地方重复使用,而无需修改它。

在选择对话框表单类中:

public string GetSelectedId()
{
    return whateverIdThatWasSelected;
}

在调用表单中:

using(var dlg = new SelectionDialogForm())
{
    if (dlg.ShowDialog() == DialogResult.OK)
    {
        DoSomethingWithSelectedId(dlg.GetSelectedId());
    }
}

【讨论】:

    【解决方案2】:

    您可以将一个属性添加到您的表单类并从您的其他表单中引用它。

    例如。

    public class FormA : Form
    {
    
    private string _YourProperty = string.empty;
    
    public string YourProperty
    {
     get
     {
      return _YourProperty;
     }
     set
     {
      _YourProperty = value;
     }
    }
    
    }
    
    public class FormB : Form
    {
    
    public void ButtonClick(object sender, EventArgs args)
    {
     using (FormA oForm = new FormA)
     {
      if (oForm.ShowDialog() == DialogResult.OK)
      {
       string Variable = oForm.YourProperty;
      }
    }
    }
    

    您只需要在表单 A 上的按钮上设置您的属性,然后您就可以从表单 B 访问它 }

    【讨论】:

      【解决方案3】:

      为什么不为对话框表单中的选定项创建一个公共属性,像这样。

      public int SelectedItemId {get;private set;}
      
      //In your item selected code, like button click handler..
      this.SelectedItemId = someValue;
      

      然后将表单作为对话框打开

      //Open the child form
      using (var form = new ChildForm())
      {
          if (form.ShowDialog(this) == DialogResult.OK)
          {
              var result = form.SelectedItemId;//Process here..
          }
      }
      

      【讨论】:

        【解决方案4】:

        做到这一点的正确方法是引入一个控制器类,这两种形式都可以使用。然后,您可以在 Controller 上使用属性,当设置该属性时将触发 NotifiyPropertyChanged 事件。

        查看INotifyPropertyChanged了解更多信息

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-02-25
          • 2015-09-21
          • 2023-03-26
          • 1970-01-01
          • 1970-01-01
          • 2020-07-26
          相关资源
          最近更新 更多