Sumit Dobriyal
Sumit Dobriyal

Reputation: 79

How to limit characters in TextBox?

I have a button1 whose text is 0, the times i click on button the button text will appear in textbox the code is mention below :

Protected Sub Button2_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button2.Click
        TextBox8.Text = TextBox8.Text + "0"
        End Sub

My problem :

i want to limit the characters print in the textbox after clicking the button1.

I want if my textbox maximum length in 2 then after 2 charcters i click on button it will not print the text of button1 after two characters.

Upvotes: 0

Views: 507

Answers (2)

Pilgerstorfer Franz
Pilgerstorfer Franz

Reputation: 8359

You may try setting MaxLength and use it to check if current text length has reached maximum

' code behind
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
    If TextBox8.Text.Length < TextBox8.MaxLength Then
        TextBox8.Text = TextBox8.Text & "0"
    End If
End Sub

' aspx page
<form id="form1" runat="server">
   <asp:TextBox ID="TextBox8" MaxLength="2" runat="server"></asp:TextBox>
   <asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />
</form>

If you could be a little bit more precise what you try to achieve, I could adapt my answer!

Upvotes: 1

Jude Fisher
Jude Fisher

Reputation: 11294

Your question is a bit hard to follow, but are you looking for the TextBox.MaxLength property?

http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.textbox.maxlength.aspx

Or, you could just check the length in code:

Protected Sub Button2_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button2.Click
    If TextBox8.Text.Length < 3 Then TextBox8.Text = TextBox8.Text + "0"
End Sub

Upvotes: 0

Related Questions