如何输入标签?

我正在尝试使用多行文本框,当您键入它时将其流式传输到标签,但标签必须具有15的最大长度,因此一旦它在文本框中达到15个字符,它应该开始覆盖标签,因为它达到了它的最大长度

感谢任何能提供帮助的人

我不确定你想要实现什么样的覆盖。

您可以使用至少三种方法:

  • 始终显示文本框中的最后15个字符 ,如Olivier的答案中所述

  • 清除标签的文本每插入15个字符并重新开始填写标签,您可以使用此代码来实现此目的:

    private void textBox1_TextChanged(object sender, EventArgs e) { String text = textBox1.Text.Replace("\r\n", "|"); int startIndex = ((text.Length - 1) / 15) * 15; label1.Text = text.Substring(Math.Max(0, startIndex)); } 
  • 当文本长度超过15个字符时 ,你也可以用char覆盖char ,但是,我想这不是你想要实现的,因为它会导致文本框中的混乱;)但是,它可以用作一种视觉效果 :)。 如果你想要这个代码片段,请告诉我:)。 更新这里是第三种覆盖方法的代码:

     String lastText = ""; private void textBox1_TextChanged(object sender, EventArgs e) { String textBoxText = textBox1.Text.Replace("\r\n", "|"); if (textBoxText.Length > lastText.Length) { int charIndex = (textBoxText.Length - 1) % 15; if (charIndex >= 0) { label1.Text = label1.Text.Insert(charIndex, textBoxText.Substring(textBoxText.Length - 1)); if (charIndex < textBoxText.Length - 1) { label1.Text = label1.Text.Remove(charIndex + 1, 1); } } } else { int charIndex = textBoxText.Length % 15; if (textBoxText.Length >= 15) { label1.Text = label1.Text.Insert(charIndex, textBoxText[textBoxText.Length - 15].ToString()); if (charIndex < textBoxText.Length - 1) { label1.Text = label1.Text.Remove(charIndex + 1, 1); } } else { label1.Text = label1.Text.Remove(label1.Text.Length - 1, 1); } } lastText = textBoxText; } 

在文本框中添加onchange事件:

 if (textBox1.Text.Length<=15) { label1.Caption=textBox1.Text; } 

例如

TextBoxTextChanged事件添加处理程序,该事件根据TextBox设置Label的内容。 例如(未经测试,可能有您的概念错误或某个地方被某个人关闭)

 int startIndex = Math.Max(0, myTextBox.Text.Length - 15); int endIndex = Math.Min(myTextBox.Text.Length - 1, startIndex); myLabel.Text = myTextBox.Text.Substring(startIndex, endIndex - startIndex); 

此外,虽然它不会改变您的问题/答案,但您可能希望使用TextBlock而不是Label 。 它允许像换行一样的东西。 在这里看到一些差异: http : //joshsmithonwpf.wordpress.com/2007/07/04/differences-between-label-and-textblock/ (在WPF中,无论你做什么,都应该是相似的)

我的解决方案始终显示标签中的最后15个字符

 private void textBox1_TextChanged(object sender, EventArgs e) { string s = textBox1.Text.Replace("\r\n", "|"); int length = s.Length; if (length > 15) { label1.Text = s.Substring(length - 15); } else { label1.Text = s; } } 

我也用|替换换行符 。 由于文本框处于多行模式,因此在按时会输入换行符。