Kendra Kendra -4 years ago 71
Vb.net Question

Cannot convert string to type 'Double'

I'm starting to code in, and learn, VB.NET. And so far, it's been smooth sailing.

Until I try to run the program.

What I've done is, in a language I know and understand, wrote a hangman game. And in C#, the code works perfectly. Once I got it to this finished point where I can say that there is nothing else I wish to change about it, I started hand-converting it to VB.NET.

So far, no problem. But I just finished converting it, and now I have hit my snag.

On the bottom of the window is a status bar, telling you which puzzle set you're in and which puzzle you're on. When selecting a puzzle, this line of code throws an error:

stsPuzzles.Text = "Puzzle: " + regionPuzzles + "/" + maxPuzzles


The error is:

Conversion from string "Puzzle" to type 'Double' is not valid.


Of course, the easy answer would be to take this mechanic out, but at least for testing purposes, I'd like it in there so I can make sure the right puzzles are in the right sets.

Is there a way I can fix this so my two integer variables can be in the string? Or is there a work around that I can at least use long enough for testing purposes for the rest of the testing process?

I'm hoping to find a way to fix this, as there are other places, such as displaying stats, that need to be able to do this.

Answer Source

The direct fix for your existing code is this:

stsPuzzles.Text = "Puzzle: " + CStr(regionPuzzles) + "/" + CStr(maxPuzzles)

or this:

stsPuzzles.Text = "Puzzle: " & regionPuzzles & "/" & maxPuzzles

In VB.Net, &, rather than +, is the concatenation operator. + will often still work, but it also has a tendency to think you wanted arithmetic when an operand is numeric.

But what I would really do in this case, is this:

stsPuzzles.Text = String.Format("Puzzle: {0}/{1}", regionPuzzles, maxPuzzles)

or with Visual Studio 2015 or later:

stsPuzzles.Text = $"Puzzle: {regionPuzzles}/{maxPuzzles}"
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download