【问题标题】:Passing data between WinForms forms [duplicate]在 WinForms 表单之间传递数据 [重复]
【发布时间】:2011-10-17 23:16:36
【问题描述】:

我在我的项目中创建了一个辅助窗体,它可以从主窗体中获取数据,并且应该在单击按钮时将一些数据传递给主窗体。
这是代码:

Add.cs:

        private void button1_Click(object sender, EventArgs e)
        {
            main ma = new main();

                ma.optionType = "add";
                ma.optionName = txtName.Text;
                ma.optionURL = txtURL.Text;
                ma.optionInterval = "12";
                //What should I pass here?


            this.Close();
        }

ma​​in.cs:

  private string opt;// create a property
        public string optionType
        {
            get
            {
                return opt;
            }
            set
            {
                opt = value;
            }
        }
        private string opt2;// create a property
        public string optionName
        {
            get
            {
                return opt2;
            }
            set
            {
                opt2 = value;
            }
        }
        private string opt3;// create a property
        public string optionURL
        {
            get
            {
                return opt3;
            }
            set
            {
                opt3 = value;
            }
        }
        private string opt4;// create a property
        public string optionInterval
        {
            get
            {
                return opt4;
            }
            set
            {
                opt4 = value;
            }
        }

我的问题是,在单击 button1(在 add.cs 中)后,我不知道何时尝试获取来自 add.cs 的数据。我应该通过什么事件检查数据是否到达?

【问题讨论】:

  • 我是你自己回答的,请随时发布答案,它可能对其他人有所帮助。

标签: c# winforms events


【解决方案1】:

如果您需要在关闭子表单之前了解更改的值,自定义事件会让您优雅地通知父表单。

这是关于 C# 中的委托和事件的精彩教程

http://www.akadia.com/services/dotnet_delegates_and_events.html

一旦子表单被实例化,父表单将注册以从子表单接收一个或多个自定义事件(根据需要)。

另一种方法是将对父表单的引用传递给子表单,以便子表单可以调用父表单的函数或属性来通知更改。但是,这种方法会在两种形式之间造成紧密耦合,因此不鼓励使用。

【讨论】:

    【解决方案2】:

    我只是把它改成这样:
    添加.cs:

     public string optionType { get; set; }
     public string optionName { get; set; }
     public string optionURL { get; set; }
     public string optionInterval { get; set; }
     public int yCoord { get; set; }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-12-03
      • 1970-01-01
      • 2011-03-05
      • 1970-01-01
      • 2022-09-29
      • 1970-01-01
      • 1970-01-01
      • 2023-03-09
      相关资源
      最近更新 更多