0

I wanted to display the remaining characters using a label beside my textbox just in case the user input exceeded the maximum length of characters.

This is my code for remaining characters:

private void txtID_TextChanged(object sender, EventArgs e)
    {
        int MaxChars = 10 - txtID.Text.Length;
        labelChars.Text = MaxChars.ToString() + " characters remaining.";
    }

What I wanted to do now is to prevent the user from entering characters in my textbox when he/she already exceeded the character limit. I'm planning to use the Substring property of the textbox but I don't know how. Help me out? Thanks.

0

5 Answers 5

2

You should use the MaxLength property. http://msdn.microsoft.com/en-us/library/system.windows.forms.textboxbase.maxlength.aspx

Sign up to request clarification or add additional context in comments.

Comments

0

You can just set the MaxLength property of the textbox and it will do that for you.

Comments

0

Could you just use the MaxLength property? http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.textbox.maxlength.aspx

Comments

0

You know the MaxLength property?

Comments

0

This would work much better on the client side. Use the MaxLength property of the textbox and maybe a little javascript to keep the lblChars control functioning.

<asp:TextBox MaxLength="10" runat="server" ID="txtID" ClientIDMode="Static" onkeydown="changedID();"></asp:TextBox>
<asp:Label ClientIDMode="Static" ID="lblChars" runat="server"></asp:Label>
<script type="text/javascript">
    function changedID() {
        var t = document.getElementById("txtID");
        var l = document.getElementById("lblChars");
        l.innerText = (10 - t.value.length) + " characters remaining.";
    }
</script>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.