VB Realtime character counter..

Soldato
Joined
13 Feb 2004
Posts
2,656
Location
South Shields
Hi,

I'm trying to write some code into a VB program that will allow a label to display the amount of characters the user has to use in realtime.

For example if the user has 50 characters to use and they enter "hello" the label will read 45 Characters left.

I have a general understanding that the code will have to flow something like this -

Dim Count As Integer
Dim Max As Integer
Dim Sum As Integer
Dim Ttl As String

Max = 50

Ttl = txttitle

Count = Ttl

Sum = Max - Count

Label2 = Sum

But as I have declared the count as Integer it will only allow integers to be used..

how would I get this code to allow me to count individual characters as they are entered and then reduce the counter in the label by 1.

I know this is probably easy to do.. but tis been a long day and my mind isn't exactly on things at the mo..

Thanks for any help..

*edit*

This is in VB6 not VB.net..
Therefore i cannot use the .length either.. :(
 
Wire up a TextChanged event on your TextBox. In that event just add some code like:

TextBox tmp = (TextBox)sender;
myLabel.Text = tmp.MaxLength - tmp.TextLength & " characters left";

My VB.NET is rusty (haven't used VB since v6) so I'm not sure if that's how you do casting in that langauge.

Edit: Oh, just saw your edit about this being for VB6. Sorry :( If I remember correctly though it will have a similar "TextChanged" event. And the code you place inside it will be almost identical...
 
How would I get a Message box to appear upon the counter hitting 0..

I currently have -

Dim Count As Integer
Dim Max As Integer
Dim Ttl As String

Max = 50

Ttl = txttitle

lbltitlechar.Caption = Max - Len(Ttl) & " characters left"

If Max = "0" Then _

MsgBox "You have reached the maximum length allowed", vbExclamation, "Maxmimum Length Reached"

End If

I've tried using When but apparently VB doesn't support it :confused:
I thought it did lol.

Would I have to apply this code to a different state.. for example lost focus,
So that when the text box has lost focus the word count is checked and if it is 0 then a message box appears..

**Edit**

Could it be done with a looping statement?
 
Im assuming "txttitle" is your input box so you could just set it's "Max Length" property to 50 so no more than 50 characters will be able to be input
 
gwfc said:
Im assuming "txttitle" is your input box so you could just set it's "Max Length" property to 50 so no more than 50 characters will be able to be input

Thanks fella..
I made a n00b error lol..

Always thinking of things in a too complicated manner.

Thanks for the help guys..
 
Back
Top Bottom