user2792683
user2792683

Reputation: 9

Type Conversion error in vb.net

Heres a bitmap image saving code snippet in vb.net. Can somebody please help me understand why am I getting an error here stating that i am trying to convert string to double while saving the image. how to correct that?

Private Sub Timer5_Tick(sender As System.Object, e As System.EventArgs) Handles Timer5.Tick
            x = MyRandomNumber.Next(1000)
            screenWidth = Screen.GetBounds(New Point(0, 0)).Width
            screenHeight = Screen.GetBounds(New Point(0, 0)).Height
            Dim bmpScreenShot As New Bitmap(screenWidth, screenHeight)
            Dim gfx As Graphics = Graphics.FromImage(bmpScreenShot)
            gfx.CopyFromScreen(0, 0, 0, 0, New Size(screenWidth, screenHeight))
        ***bmpScreenShot.Save("D:\\screenshots\\" + x + ".jpg", System.Drawing.Imaging.ImageFormat.Jpeg)***
    End Sub

Upvotes: 0

Views: 241

Answers (3)

sloth
sloth

Reputation: 101142

"D:\\screenshots\\" is as string. x is a double.

You try to add "D:\\screenshots\\" and x, and this fails, because "D:\\screenshots\\" is not a double.

That's what the compiler tries to tell you.


Have a look at the documentation of the + operator:

In general, + performs arithmetic addition when possible, and concatenates only when both expressions are strings.

Data types of expressions:

Object expression holds a numeric value and the other is of type String

Action by compiler:

If Option Strict is On, then generate a compiler error.

If Option Strict is Off, then implicitly convert the String to Double and add.

If the String cannot be converted to Double, then throw an InvalidCastException exception.


To concatenate strings use the & operator:

Generates a string concatenation of two expressions.

... "D:\\screenshots\\" & x & ".jpg"...

or String.Format:

String.Format("D:\\screenshots\\{0}.jpg", x)

Lesson learned:

Always use Option Strict On, and always look up the documentation.

Upvotes: 3

Markus
Markus

Reputation: 22501

Use & instead of + to concatenate the path:

bmpScreenShot.Save("D:\\screenshots\\" & x & ".jpg", System.Drawing.Imaging.ImageFormat.Jpeg)

Upvotes: 1

Dmytro Rudenko
Dmytro Rudenko

Reputation: 2524

bmpScreenShot.Save("D:\\screenshots\\" + x.ToString() + ".jpg", System.Drawing.Imaging.ImageFormat.Jpeg)

Upvotes: 1

Related Questions