C#文本框消息

问题描述:

如果在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

我假设你正在使用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开头和邮件的末尾,你可以将它添加到该行的末尾。

希望帮助:)

只要文本框失去焦点就打开一个消息框与您的消息,然后再次给文本框的焦点,将其更改为验证。这将确保用户不能输入不符合约束条件的值。

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

您使用+ =,如果TextBox1的文本以这种增加每次的错误信息 “ - ”。如果你想添加这一次删除+ =并且只添加=

您目前通过+=运算符将错误消息连接到文本框的内容,但实际上只需将其设置为该值即可通过使用=操作:

// 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" : "";