且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将值从一个表单中的一个文本框传递到另一个表单中的另一个文本框

更新时间:2023-02-11 19:17:03

humm我会说你做了世界上最简单的任务的复杂方法之一。



你听说过C#中的属性吗? ??

如果是我的话。我将Text2中的TextBox作为Get only属性公开,并使用该对象在我的父表单中更新。

例如:



humm I would say you have done one of the complex way to doing a simplest task in the world.

Have you heard about Properties in C#. ??
If it was me. I would expose the TextBox from the Form2 as a Get only property and use that object to update in my parent form.
eg:

public partial class Form1 : Form
{
   public Form1()
   {
      InitializeComponent();
   }

   private void button1_Click(object sender, EventArgs e)
   {
      Form2 f2 = new Form2();
      if( f2.ShowDialog() == DialogResult.OK)
      {
        textBox1.text = f2.TxtBox.Text;
      }
    }   
}

public partial class Form2 : Form
{
    public TextBox TxtBox
    {
      get {return textBox1;}
    }
    public Form2()
    {
       InitializeComponent();
    }
}


您好,



更改 Form2 上课:

Hi,

Change the Form2 class into this:
public partial class Form2 : Form
    {
        Form1 f1 = null;
        public Form2(Form1 _form1)
        {
            InitializeComponent();
            f1 = _form1;
        }
        private void button1_Click(object sender, EventArgs e)
        {
            if (f1 == null)
                f1 = new Form1();
            f1.valuefromform2(textBox1.Text);
            f1.Show();
        }
 

    }



并更改 button1_Click 功能如下:


And change the button1_Click function into this:

private void button1_Click(object sender, EventArgs e)
       {
           Form2 f2 = new Form2(this);
           f2.Show();

       }



希望这会有所帮助。


Hope this helps.


这是关于表单的热门问题合作。最强大的解决方案是在表单类中实现适当的接口,并传递接口引用而不是引用Form的整个实例。有关更多详细信息,请参阅我以前的解决方案:如何以两种形式复制列表框之间的所有项目 [ ^ ]。



另请参阅此处的其他解决方案讨论。如果应用程序足够简单,解决方案就像在一个表单中声明一些 internal 属性并将对一个表单的实例的引用传递给另一个表单的实例一样简单形成。对于更复杂的项目,这种违反严格封装的样式和松散耦合可能会增加代码的意外复杂性并引发错误,因此封装良好的解决方案将是优惠。



另请参阅:

http://en.wikipedia.org/wiki/Accidental_complexity [ ^ ],

http://en.wikipedia.org/wiki/Loose_coupling [ ^ ]。



-SA
This is the popular question about form collaboration. The most robust solution is implementation of an appropriate interface in form class and passing the interface reference instead of reference to a "whole instance" of a Form. Please see my past solution for more detail: How to copy all the items between listboxes in two forms[^].

Please also see other solutions in this discussion. If the application is simple enough, the solution could be as simple as declaring of some internal property in one form and passing a reference to the instance of one form to the instance of another form. For more complex projects, such violation of strictly encapsulated style and loose coupling could add up the the accidental complexity of the code and invite mistakes, so the well-encapsulated solution would be preferable.

Please see also:
http://en.wikipedia.org/wiki/Accidental_complexity[^],
http://en.wikipedia.org/wiki/Loose_coupling[^].

—SA