繁体   English   中英

检查用户是否在文本框中输入单个字符或数字c#

[英]Check if user type a single character or number in textbox c#

我已经可以为用户登录了,因此,如果用户在文本框中输入了错误的用户名或密码,则会显示“ 无效的用户名或密码 ”消息标签。 但是,我想当用户在出现消息标签时在文本框中键入单个字符或数字时,消息标签对用户不可见( visible = false ),因为用户已经在文本框中键入了单个字符或数字。 但是,当用户键入单个字符或数字时,消息标签并没有消失。

这是代码:

private void CheckTextBox(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(textBox1.Text) || string.IsNullOrEmpty(textBox2.Text))
            {
                label5.Visible = true;
            }

            else
            {
                label5.Visible = false;
            }
        }

这是图片:

下图是当用户键入错误(用户名或密码)时,出现消息标签:

在此处输入图片说明

下图是当用户键入单个字符或数字但消息标签仍在此处时

在此处输入图片说明

我的问题是:当用户在文本框中键入单个字符或数字时,如何设置消息标签不显示?

有什么帮助吗?

您的回答将不胜感激!

谢谢!

问题:您尚未为TextBox1TextBox2 TextChanged事件连接CheckTextBox()方法。

解决方案:在您的Form_Load WireUp中, Textbox1TextBox2 TextChanged事件的CheckTextBox()方法如下:

  private void Form1_Load(object sender, EventArgs e)
    {
      textBox1.TextChanged += new System.EventHandler(this.CheckTextBox);
      textBox2.TextChanged += new System.EventHandler(this.CheckTextBox);
    }

建议:我认为string.IsNullOrWhiteSpace()是比较合适的,因为它也将检查Whitespace除了nullEmpty字符串。

尝试这个:

   private void CheckTextBox(object sender, EventArgs e)
    {
        if (string.IsNullOrWhiteSpace(textBox1.Text) || string.IsNullOrWhiteSpace(textBox2.Text))
        {
            label5.Visible = true;
        }

        else
        {
            label5.Visible = false;
        }
    }

此行正在检查其中任一文本框是否包含信息。

if (string.IsNullOrEmpty(textBox1.Text) || string.IsNullOrEmpty(textBox2.Text))

更改|| && ,然后只有两个文本框都没有数据时才会显示标签。

如果我对您的理解正确,请尝试以下操作:

private void CheckTextBox(object sender, EventArgs e)
{
     if (string.IsNullOrEmpty(textBox1.Text) && string.IsNullOrEmpty(textBox2.Text))
     {
         label5.Visible = true;
     }

     else
     {
         label5.Visible = false;
     }
}

如果您更改|| &&则只有两个文本框都为空时, label5才可见。

检查此代码, 应在文本框中将其称为OnTextChanged =“ CheckTextBox”

protected void CheckTextBox(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(textBox1.Text) && string.IsNullOrEmpty(textBox2.Text))
            {
                label5.Visible = true;
            }

            else
            {
                label5.Visible = false;
            }
        }

<asp:TextBox ID="TextBox1" runat="server" OnTextChanged="CheckTextBox"></asp:TextBox>
if (string.IsNullOrEmpty(textBox1.Text) || string.IsNullOrEmpty(textBox2.Text))

试试这个..使用&&代替||

private void CheckTextBox(object sender, EventArgs e)
{
     if (string.IsNullOrEmpty(textBox1.Text) && string.IsNullOrEmpty(textBox2.Text))
     {
         label5.Visible = true;
     }

     else
     {
         label5.Visible = false;
     }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM