显示剩余文本框字符 C#

发布于 2024-12-13 18:03:49 字数 243 浏览 1 评论 0原文

我只是想知道如何在文本框中显示剩余字符,以防用户输入超出字符限制。

例如,这是我的文本框:

输入名称:_____________ 剩余 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

空城旧梦 2024-12-20 18:03:49

First 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 subtracting textBox.MaxLength by textBox.TextLength

吻安 2024-12-20 18:03:49

您需要 TextBoxMaxLength 属性。

您可以通过在文本框的正确大小上使用标签来实现您想要的效果。对于输入的每个键,您可以将该标签的标题更新为 $"{textbox1.MaxLength - textbox1.Text.Length()} 个字符"

You need TextBox's MaxLength 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".

蹲在坟头点根烟 2024-12-20 18:03:49

将其放入文本框更改事件中。

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.

遇到 2024-12-20 18:03:49

首先,不清楚,但看起来您也将 Name: 部分放入文本框中,这实际上应该放在标签中。剩下的角色也是如此。

至于计算剩余字符,请使用文本框的KeyPress事件。

您该事件的代码将是这样的

private void textBox_KeyPress(object sender, EventArgs e)
{
    var max = 100;
    label.Text = (max - this.Text) + " Characters remaining);
}

希望这会有所帮助。

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

private void textBox_KeyPress(object sender, EventArgs e)
{
    var max = 100;
    label.Text = (max - this.Text) + " Characters remaining);
}

Hope this helps.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文