单击按钮将值从一种形式传递到另一种形式 [英] Passing Values from one Form to another Form in a Button click
问题描述
这些是我的2种表格.
These are my 2 Forms.
这些是表格1的代码->
These are the codes for Form 1-->
namespace Passing_Values
{
public partial class Form1 : Form
{
string a="preset value";
public Form1()
{
InitializeComponent();
}
private void btnOpenF2_Click(object sender, EventArgs e)
{
new Form2().Show();
}
public void set(string p)
{
MessageBox.Show("This is Entered text in Form 2 " + p);
a = p;
MessageBox.Show("a=p done! and P is: " + p + "---and a is: " + a);
textBox1.Text = "Test 1";
textBox2.Text = a;
textBox3.Text = p;
}
private void button2_Click(object sender, EventArgs e)
{
MessageBox.Show(a);
}
}
}
这些是表格2->
namespace Passing_Values
{
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string g;
g = textBox1.Text;
Form1 j = new Form1();
j.set(g);
}
}
}
查看图片.您可以了解设计.
See the picture.You can understand the design.
这就是我想要做的.首先,我使用Form1中的按钮打开Form2.然后,我输入一个文本并单击按钮(在Form1文本框中显示").单击该值时,应该在Form1的3个文本框中看到该值.我使用消息框来查看这些值是否通过.值从Form2传递到Form1.但是这些值不会显示在这3个文本框中,而传递的值将显示在消息框中.通过查看代码可以理解3个文本框的原因.那怎么了?
This is what I want to do. 1st I open Form2 using button in Form1. Then I enter a text and click the button("Display in Form1 Textbox"). When it's clicked that value should be seen in the 3 Textboxes in Form1.I used Message Boxes to see if the values are passing or not. Values get passed from Form2 to Form1. But those values are not displays in those 3 Textboxes but the passed values are displayed in Message Boxes. Reason for the 3 Text Boxes can be understood by looking at the code. So what's the error?
推荐答案
实际上我有一个要传递的对象.所以我做到了
Actually I have an object to pass. So I did this
form1->
private void btnOpenF2_Click(object sender, EventArgs e)
{
new Form2(this).Show();
}
form2->
public partial class Form2 : Form
{
Form1 a;
public Form2(Form1 b)
{
a = b;
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string g;
g = textBox1.Text;
a.set(g);
this.Close();
}
}
这篇关于单击按钮将值从一种形式传递到另一种形式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!