簡體   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