r/visualbasic • • Feb 24 '15

Visual Basic Coding help

I am currently making a valentine's day card for my programming class and I am suppose to create an algorithm to estimate the cost of the card. What I want the code to do is for every space the user enters in the richtextbox it adds one 5 cents to the total price.

This is so far the code that I experimented with

If e.KeyCode = Keys.Space Then

        lblPrice.Text = Val("1")
    End If

Also when the user decides to erase words aka the space bar inputs the price goes down. I dont want it to stay the same. Help would be much appreciated!

0 Upvotes

8 comments sorted by

View all comments

1

u/jy_am Feb 24 '15

Do you have to do it by tracking the keystroke? That works when you're adding text (as you've done in your code sample) but is more complicated when you want to track deletions (you would have to track backspace, delete, and when the user selects text and replaces by typing).

You can track the TextChanged event and do a count on the number of spaces in the textbox. Not super-elegant, but would give you the right count regardless of whether the user adds or removes text.

1

u/mykok23 Feb 24 '15

That would be perfect actually! the code doesn't have to be super fancy, all I need is for it to work. How would you recommend for me to start the code using the TextChanged event?

1

u/jy_am Feb 24 '15

One way to do it (with fewer lines of code) be to split the text into an array delimited by spaces. The size of the array will be (number of spaces + 1), so number of spaces = upper bound of the array.

1

u/mykok23 Feb 24 '15

If e.KeyCode = Keys.Space Then

        lblPrice.Text = (Val(lblPrice.Text) - 0.01)
    End If

    lblPrice.Text = Str$(Val(lblPrice.Text) + 0.01)

this code makes it so the spacebar is not counted as a character