在WinForms表单之间传递数据

时间:2011-10-17 23:16:36

标签: c# winforms events

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

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

main.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的数据。我应该在什么事件中检查数据是否来了?

2 个答案:

答案 0 :(得分:0)

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

这是关于C#

中的委托和事件的精彩教程

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

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

另一种方法是将对父表单的引用传递给子表单,以便子表单可以调用父表单的函数或属性来通知更改。然而,这种方法在两种形式之间产生紧密耦合,并且不鼓励。

答案 1 :(得分:0)

我刚把它改成了这个:
add.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; }
相关问题