[英]Changing Label From Another Form
I've already searched other questions for this answer (and that is how I got as far as I did) and everything seems to be working except the end result. 我已经在其他问题上搜索了此答案(这就是我得到的答案),除最终结果外,其他所有功能似乎都在起作用。 I am getting no errors but I am not getting the desired input and cannot figure out why. 我没有收到任何错误,但没有得到所需的输入,无法弄清原因。
I have two forms, Form1 and login. 我有两种形式,Form1和登录名。 On Form1 I have a label called "label2" that is going to display text entered from a textbox on login upon button press. 在Form1上,我有一个名为“ label2”的标签,它将在按下按钮时登录时显示从文本框输入的文本。 Here is the code I have so far: 这是我到目前为止的代码:
Form1 Code: Form1代码:
public void SetTextForLabel(string myText)
{
this.label2.Text = myText;
}
login Code: 登录代码:
private void button1_Click(object sender, EventArgs e)
{
Form1.userName = textBox1.Text;
Form1.password = textBox2.Text;
Form1 frm = new Form1();
frm.SetTextForLabel(textBox1.Text);
this.Close();
}
The program works. 该程序有效。 I click login on form1, it opens up the login form. 我单击form1上的login,它将打开登录表单。 I enter my username and password and it passes the input to my form1 variables. 我输入我的用户名和密码,并将输入内容传递给form1变量。 Since label2 on form1 is not public, I made a public method to use on my login form that will change my label2.Text, but it doesn't and I'm not sure why. 由于form1上的label2不公开,因此我在登录表单上使用了一个公共方法,该方法将更改我的label2.Text,但是它不是,并且我不确定为什么。 Any help would be appreciated. 任何帮助,将不胜感激。
Judging from your description, I believe Form1 opens Login form, and on login form there is button1
that is probably your login button. 从您的描述来看,我相信Form1会打开Login表单,并且在登录表单上有button1
可能是您的登录按钮。
If this is all correct then I think you have your logic wrong. 如果一切正确,那么我认为您的逻辑有误。
your button on Form1 that opens login form should do the following 您在Form1上用于打开登录表单的按钮应该执行以下操作
using(Login loginForm = new Login())
{
if(DialogResult.OK == loginForm.ShowDialog())
{
SetTextForLabel(loginForm.TextAccessorProperty);
}
else
{
MessageBox.Show("Invalid login");
}
}
then login forms button one should just do, 然后应该先登录表单按钮,
//Login logic
this.DialogResult = DialogResult.OK;
// (no need for form.close())
This creates a new instance of Form1
but it's not shown, and I suspect this is not the reference you need. 这将创建一个新的Form1
实例,但未显示,我怀疑这不是您需要的引用。
Form1 frm = new Form1();
frm.SetTextForLabel(textBox1.Text);
Your code works fine for me, Just write one more line to show form1. 您的代码对我来说很好,只需再写一行以显示form1。
ie 即
frm.Show();
I think it will work. 我认为它将起作用。 :) :)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.