显示剩余文本框字符 C#
我只是想知道如何在文本框中显示剩余字符,以防用户输入超出字符限制。
例如,这是我的文本框:
输入名称:_____________ 剩余 50 个字符
当用户输入已经是 50 个字符时,他/她将无法再在该文本框中输入任何内容。这可能吗?任何帮助将不胜感激。提前致谢。
I just wanted to know how to display the remaining characters in my textbox, just in case the user input exceeded the character limit.
For example, here is my textbox:
Enter Name: _____________ 50 Characters remaining
And when the user input is already 50 characters, he/she won't be able to type anything in that textbox anymore. Is that possible? Any help would be appreciated. Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
首先,设置文本框的MaxLength 属性 至 50。
然后,您需要订阅文本框的
TextChanged
事件,以便在文本框的文本发生更改时收到通知,并通过将textBox.MaxLength
减去 <代码>textBox.TextLengthFirst you set the MaxLength property of the textbox to 50.
Then you need to subscribe to the
TextChanged
event of the textbox to be notified when the text of the box has changed, and calulate the remaining characters by subtractingtextBox.MaxLength
bytextBox.TextLength
您需要
TextBox
的MaxLength
属性。您可以通过在文本框的正确大小上使用标签来实现您想要的效果。对于输入的每个键,您可以将该标签的标题更新为
$"{textbox1.MaxLength - textbox1.Text.Length()} 个字符"
。You need
TextBox
'sMaxLength
property.You can achieve what you want by using a label on the right size of your text box. On every key entered, you can update that label's caption to
$"{textbox1.MaxLength - textbox1.Text.Length()} characters"
.将其放入文本框更改事件中。
labelForRemainingChars.Caption = txtMyTextBox.MaxLength - txtMyTextBox.TextLength;
编辑:这适用于 winforms。
Put this in the textbox change event.
labelForRemainingChars.Caption = txtMyTextBox.MaxLength - txtMyTextBox.TextLength;
EDIT: This is applicable to winforms.
首先,不清楚,但看起来您也将
Name:
部分放入文本框中,这实际上应该放在标签中。剩下的角色也是如此。至于计算剩余字符,请使用文本框的
KeyPress
事件。您该事件的代码将是这样的
希望这会有所帮助。
Firstly, it's not clear but it looks like your putting the
Name:
part in the text box too, that should really go in a label. The same goes for the characters remaining.As for calculating the remaining chars, use the
KeyPress
event of the textbox.Your code for that event will be something like this
Hope this helps.