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

时间:2013-06-04 00:31:40

标签: c# textbox character

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

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

2 个答案:

答案 0 :(得分:5)

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 like in this link

答案 1 :(得分:3)

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

标题代码:

<script language="javascript" type="text/javascript">
    function getCountDown() 
    {
        //Get the Textbox control
        var textField = document.getElementById("<%#TextBox1.ClientID %>");
        //Do the math of chars left and pass the value to the label
        document.getElementById('<%#Label1.ClientID %>').innerHTML = textField.maxLength - textField.value.length;
        return false;
    }        
</script>

ASP代码:

<asp:TextBox ID="TextBox1" runat="server" MaxLength="729" Height="80px" 
                Width="591px" onkeyup="getCountDown();" ClientIDMode="Static"></asp:TextBox>

<asp:Label ID="Label1" runat="server" Text="" ClientIDMode="Static"></asp:Label>

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());

MaxLength处于TextBox模式时,Multiline的{​​{1}}属性也不起作用,因此您需要在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 %>");行之后添加它们。这是为了防止用户输入比MaxLength值更多的字符。

巴勃罗