2016-05-31 83 views
-1

如果在textBox1第一行以「 - 」開頭,我嘗試在textBox2中顯示消息。 好吧,但如果我輸入「 - 你好」或其他以「 - 」開頭的程序,請添加所有時間消息「請勿使用其他字符」。 有什麼方法可以發送一次嗎?C#文本框消息

if(textBox1.Text.StartsWith("-")) 
{ 
    textBox2.Text += "\r\n Please do not use other characters \r\n"; 
} 
+0

而不是'+ ='使用'='? – CodeCaster

+0

我希望程序在textbox1以「 - 」開頭時始終添加消息 –

+5

請編輯您的問題,以便它包含您想要發生的事情以及您認爲「全天候」意味着的一步一步。 – CodeCaster

回答

0

我假設你正在使用textBox2顯示多條消息(因此您使用的是=+而不是=),但如果用戶仍在鍵入,則不希望兩次顯示相同的消息。

如果是這樣的話,你可以使用任何的這3個選項:

1要使用Leave事件..像下面這樣:

private void textBox1_Leave(object sender, EventArgs e) 
    { 
     if (textBox1.Text.StartsWith("-")) 
     { 
      textBox2.Text += "\r\n Please do not use other characters \r\n"; 
     } 
    } 

在這種情況下,僅在textBox1失去焦點時纔會顯示該消息。


2 - 如果你想顯示在打字,但要顯示一個時間的消息,你可以做這樣的事情:

bool Alerted; 
    private void textBox1_Enter(object sender, EventArgs e) 
    { 
     Alerted = false; 
    } 
    private void textBox1_TextChanged(object sender, EventArgs e) 
    { 
     if (Alerted) { return; } 
     if (textBox1.Text.StartsWith("-")) 
     { 
      Alerted = true; 
      textBox2.Text += "\r\n Please do not use other characters \r\n"; 
     } 
    } 

這將不顯示消息直到textBox1重新獲得關注。


3-如果你想除非永遠不會被再次顯示消息( - )被刪除,再次輸入,則不要使用Enter,並且你可以使用以下命令:

bool Alerted; 
    private void textBox1_TextChanged(object sender, EventArgs e) 
    { 
     if (textBox1.Text.StartsWith("-")) 
     { 
      if (Alerted) { return; } 
      Alerted = true; 
      textBox2.Text += "\r\n Please do not use other characters \r\n"; 
     } 
     else 
     { 
      Alerted = false; 
     } 
    } 

一個最後一個音符:你可能不需要\r\n開頭和郵件的末尾,你可以將它添加到該行的末尾。

希望幫助:)

0

只要文本框失去焦點就打開一個消息框與您的消息,然後再次給文本框的焦點,將其更改爲驗證。這將確保用戶不能輸入不符合約束條件的值。

0
if(textBox1.Text.StartsWith("-")) 
{ 
    textBox2.Text = "\r\n Please do not use other characters \r\n"; 
} 
else 
    textBox2.Text = ""; 

您使用+ =,如果TextBox1的文本以這種增加每次的錯誤信息 「 - 」。如果你想添加這一次刪除+ =並且只添加=

0

您目前通過+=運算符將錯誤消息連接到文本框的內容,但實際上只需將其設置爲該值即可通過使用=操作:

// If your TextBox starts with "-" 
if(textBox1.Text.StartsWith("-")) 
{ 
    // Set your textbox to the error message 
    textBox2.Text = "\r\n Please do not use other characters \r\n"; 
} 
else 
{ 
    // Otherwise, there isn't a problem (remove any error messages) 
    textBox2.Text = ""; 
} 

如果您首選較短的方法,下面會做同樣的事情:

// This will handle all of your logic in a single line 
textBox2.Text = textBox1.Text.StartsWith("-") ? "\r\n Please do not use other characters \r\n" : "";