Csharp/C#教程:从form2上的另一个文本框中的form1上的一个文本框中获取数据分享


从form2上的另一个文本框中的form1上的一个文本框中获取数据

我有两种formsform1和form2。 我想在form1上单击一个按钮时从form2的文本框中获取文本。 我在form1上使用:

private void but_Click(object sender, EventArgs e) { Form2 f2=new Form2(); txtonform1=f2.fo; } 

form2我有这个方法从文本框中返回文本:

 public string fo { get { return textBox1.Text; } set { textBox1.Text = value; } } 

现在的问题是它返回null 。 是什么问题我是新来的c#可以请任何人帮助我!

您必须使用一个表单,否则每次都创建新实例:

 Form2 f2 = new Form2(); private void but1_Click(object sender, EventArgs e) { f2.fo=txtonform1.Text; } private void but2_Click(object sender, EventArgs e) { MessageBox.Show(f2.fo); } 

您正在此处创建新的表单实例:

  Form2 f2=new Form2(); 

并且你的fo属性返回这个新表单的textBox1 ,所以你textBox1不包含任何文本,你得到null。

我猜你是从Form1显示form2,如果它是正确的只是在类级别定义一个Form2 intance:

 public partial class Form1 : Form { Form2 f2 = new Form2(); } 

当你想要显示它时使用这个:

 f2.Show(this); 

如果要立即更改TextBox值,可以使用:

 txtonform1.Text = f2.fo; 

但要做到这一点,请确保在form2中更改textBox1.Text。

您应该在form1保留已经显示/的form2的引用,然后使用相同的变量来访问该值。

我不知道form2是如何创建和显示的,但假设它是创建并通过某个按钮显示在form1单击,那么form1类将看起来像,

 private Form f2 = null; private void buttonShowForm2_Click(object sender, EventArgs e) { if(f2 == null) f2 = new form2(); f2.Show(); } private void but_Click(object sender, EventArgs e) { if(f2 == null) //If this form was not already displayed display it to get the input from user buttonShowForm2_Click(null, null); else txtonform1=f2.fo; } 

第一个解决方案:

1.)转到Form2然后双击它。 在代码类型这个。

 public Form2(string sTEXT) { InitializeComponent(); textBox1.Text = sTEXT; } 2.) Goto Form1 then Double click it. At the code type this. //At your command button in Form1 private void button1_Click(object sender, EventArgs e) { Form2 sForm = new Form2(textBox1.Text); sForm.Show(); } 

第二个解决方案:

1.)转到Form1然后双击它。 在代码类型这个。

 public string CaptionText { get {return textBox1.Text;} set { textBox1.Text = value;} } 

注意:textbox1.text = sayre的值;

2.)转到Form2然后双击它。 在代码类型这个。

上述就是C#学习教程:从form2上的另一个文本框中的form1上的一个文本框中获取数据分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!

 // At your command button In Form2 private void button1_Click(object sender, EventArgs e) { Form1 sForm1 = new Form1(); textBox1.Text = sForm1.CaptionText; } 

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/cdevelopment/1031366.html

(0)
上一篇 2022年1月13日
下一篇 2022年1月13日

精彩推荐