C# 访问其他表单值
我有两张表格,即表格1和表格2 在Form1中,我有一个名为“HumanName”的字符串,这个“HumanName”有一个来自textbox.text的值。我还有一个叫Button1的按钮 在Form2中,我有一个名为Label1的标签 这就是我想要完成的。 当我点击/按下按钮1时,C# 访问其他表单值,c#,winforms,C#,Winforms,我有两张表格,即表格1和表格2 在Form1中,我有一个名为“HumanName”的字符串,这个“HumanName”有一个来自textbox.text的值。我还有一个叫Button1的按钮 在Form2中,我有一个名为Label1的标签 这就是我想要完成的。 当我点击/按下按钮1时,Label1.Text=HumanName 表格1: HumanName = textbox.text, Button1 表格2: Label1.Text = HumanName 这是我的密码: public
Label1.Text=HumanName
表格1:
HumanName = textbox.text, Button1
表格2:
Label1.Text = HumanName
这是我的密码:
public partial class Form1 : Form
{
private void PersonalInformationToForm2()
{
HumanName = textBox_Name.Text;
}
private void Button1_Click(object sender, EventArgs e)
{
PersonalInformationToForm2();
}
}
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
Label1.Text=HumanName; //I need the value of HumanName from Form1
}
}
为Form2创建一个采用人名的构造函数
然后,按下Form1中的按钮,创建表单的新实例并传入Textbox1。Form2中的Text以以下方式创建构造函数
public void Form2(string name)
{
Label1.Text=name;
}
string HumanName=textbox.text;
Form2 frm2=new Form2(HumanName);
frm2.Show();
表1中的Noe我们可以用以下方式发送值
public void Form2(string name)
{
Label1.Text=name;
}
string HumanName=textbox.text;
Form2 frm2=new Form2(HumanName);
frm2.Show();
为Form1创建一个实例,该实例可用于Form2。您可以这样做:
public static Form2 Instance;
public Form2()
{
InitializeComponent();
Instance = this;
}
在属性中将Label1的修改器设置为true
按下Form1上的按钮1时,请执行以下操作:
private void Button1_OnClick(object sender, EventArgs args)
{
Form2.Instance.Label1.Text = textBox1.Text;
}
在Form1上,将控件封装在属性中
public string GetTextboxText {get{ return Textbox1.Text;}}
另一方面
var formOne = (Form1)Application.OpenForms["Form1"];
Label1.Text = formOne.GetTextboxText;
看看您可以找到已打开的表单,并根据需要访问其属性/方法。对于您的场景,这可能有点过分,但一般来说,您可以将控件绑定到同一个源,其中包含属性HumanName(带有HumanNameChanged事件)。然后,当属性更改时,所有绑定控件都会更新其显示(即使有更多form1和form2的实例),我认为[这是][1]您要搜索的内容。;)[1] :这不是构造函数,应该重载构造函数,如:
public Form2(字符串名称){Label1.Text=name;}