【发布时间】:2015-01-18 05:43:10
【问题描述】:
所以我尝试检查两个文本框以确保它们相互匹配,然后在标签中我想说“密码匹配”或“密码不匹配”。
好吧,我大部分都在工作,但如果两个文本框都没有任何内容,我希望标签可见。无论我尝试什么,当两个文本框都为空时,我都会不断收到“密码匹配”。
总而言之,用户将密码堆栈输入到两个文本框中,标签应为“密码匹配”,但如果用户从文本框中删除两个密码,我希望标签消失。我要消失的标签称为“lblPWCountAgain”,文本框称为“txtPassword”和“txtPasswordAgain”
但是我在密码框下设置了它,所以它告诉用户他们还剩下多少个字符可以在文本框中输入。此标签仅在用户关注文本框时显示,因此在他们关注之前它是不可见的。 “密码匹配”和“密码不匹配”标签的设置方式相同。如果用户在两个文本框中输入相同的密码,则背景颜色变为绿色,如果输入的密码不匹配,则背景颜色变为红色。
所以我通过执行以下操作将文本框 TextChanged 事件设置为“textbox_TextChangedCompare”:
txtPassword.TextChanged += textbox_TextChangedCompare;
txtPasswordAgain.TextChanged += textbox_TextChangedCompare;
在 textbox_TextChangedCompare 我有:
string pw = txtPassword.Text;
string pwa = txtPasswordAgain.Text;
if (pw == pwa)
{
lblPWCountAgain.Visible=true;
lblPasswordCount.Text = "Passwords Match";
lblPWCountAgain.Text = "Passwords Match";
}
else if (string.IsNullOrEmpty(pw) && string.IsNullOrEmpty(pwa))
{
lblPWCountAgain.Visible=false;
}
else
{
lblPWCountAgain.Visible = true;
lblPWCountAgain.text = "Passwords do not match!";
var passw = txtPassword.MaxLength - txtPassword.Text.Length;
lblPasswordCount.Text = passw.ToString();
}
// I also just tried to use this as well
if (pw == "" && pwa == "")
{
lblPWCountAgain.Visible = false;
var passw = txtPassword.MaxLength - txtPassword.Text.Length;
lblPasswordCount.Text = passw.ToString();
}
这是对焦的代码:
var password = txtPassword.MaxLength - txtPassword.Text.Length;
if (txtPassword.Focused)
{
lblPasswordCount.Visible = true;
lblPasswordCount.Text = password.ToString() + " Characters remaining";
}
else
{
lblPasswordCount.Visibe = false;
}
所以对于背景颜色的更改,我这样做了:
// I set the KeyUp event to textbox_Compare:
txtPassword.KeyUp += textbox_Compare;
txtPasswordAgain.KeyUp += textbox_Compare;
private void textbox_Compare(object sender, KeyEventArgs e)
{
Color bgColor = new Color();
if (txtPassword.Text != txtPasswordAgain.Text)
{
bgColor = Color.Red;
}
else
{
lblPWCountAgain.Visible = true;
bgColor = Color.LightGreen;
}
if (txtPassword.Text == String.Empty && txtPasswordAgain.Text == String.Empty)
{
bgColor = SystemColors.ControlLightLight // This is the background color of the textbox by default
}
txtPassword.BackColor = bgColor;
txtPasswordAgain.BackColor = bgColor;
}
我不确定我只是在代码中重复自己还是什么,但我无法弄清楚。它可能不是最好的代码,但我正在尽可能多地学习它!
感谢大家的帮助
【问题讨论】:
标签: c# winforms validation textbox