如何在C#中显示标签中的剩余文本框字符?

我不确定我的最后一点是否合适? 我将文本框的最大长度更改为140.我似乎无法使用TextLength 。 请帮忙?! 到目前为止我有这个:

 protected void textBox_TextChanged(object sender, EventArgs e) { characterCountLabel.Text = textBox.MaxLength - textBox.TextLength; } 

characterCountLabel.Text是字符串格式。 所以你可能想要在设置它的值之前转换它:

 protected void textBox_TextChanged(object sender, EventArgs e) { characterCountLabel.Text = (textBox.MaxLength - textBox.Text.Length).ToString(); } 

我想您正在尝试显示用户可以输入到文本框的剩余字符? 我建议您可以将限制设置为常量,如下所示:

 protected void textBox_TextChanged(object sender, EventArgs e) { characterCountLabel.Text = (140 - textBox.Text.Length).ToString(); // in here 140 is your limit } 

如果您在C#中使用ASP.NET。 不要限制自己使用此链接中的 javascript

我认为这将是一个更好的答案……

标题代码:

  

ASP代码:

   

TextBoxLabel控件的属性设置为ClientIDMode="Static"非常重要,否则将无法在javascript上找到控件名称。

CS代码:

 protected void Page_Load(object sender, EventArgs e) { Page.Header.DataBind(); } 

这就是SingleLine TextBox。

现在对于MultiLine TextBox您需要在Page_Load()上添加它,以便maxLength采用TextBox1.MaxLength值:

 this.TextBox1.Attributes.Add("maxLength", TextBox1.MaxLength.ToString()); 

Multiline模式下, TextBoxMaxLength属性也不起作用,因此您需要在javascript getCountDown()函数中添加以下行:

 // Check if user is entering more than the limit of characters if (textField.value.length >= textField.maxLength) { // Cut extra text document.getElementById("<%#TextBox1.ClientID %>").innerHTML = textField.value.substring(0, textField.maxLength); } 

var textField = document.getElementById("<%#TextBox1.ClientID %>");之后添加它们var textField = document.getElementById("<%#TextBox1.ClientID %>"); 线。 这是为了防止用户输入比MaxLength值更多的字符。

巴勃罗