在WinForms表单之间传递数据

本文关键字:数据 之间 WinForms 表单 | 更新日期: 2023-09-27 18:11:26

我在我的项目中做了一个二级表单,可以从主表单中获取数据,并且应该在单击按钮时传递一些到主表单。
下面是代码:

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

c:

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

我的问题是,我不知道什么时候试图获取数据从add.cs后按钮1(在add.cs)被点击。我应该用什么事件来检查数据是否来了?

在WinForms表单之间传递数据

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

这是一个关于c#委托和事件的很棒的教程

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

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

另一种方法是将对父窗体的引用传递给子窗体,以便子窗体可以调用父窗体的函数或属性来通知更改。但是,这种方法会在两个表单之间产生紧密耦合,因此不建议使用。

我只是把它改成了:
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; }