Stuneris
Stuneris

Reputation: 77

Visual Basic 2013 Color to code

I wanna make color selector, when picked color write color code to text box. I created color dialog and text boxes, how make a rgb and hex codes from picked color?

I'm trying this code, but it have a problem:

TextBox1.Text = ColorDialog1.Color.R + ", " + ColorDialog1.Color.G + ", " + ColorDialog1.Color.B

Getting:

An unhandled exception of type 'System.InvalidCastException' occurred in Microsoft.VisualBasic.dll Additional information: Conversion from string ", " to type 'Double' is not valid.

Upvotes: 1

Views: 1486

Answers (2)

Basic
Basic

Reputation: 26766

Something like this will get you what you need...

Dim MyColor = Color.LightGreen

Dim R = MyColor.R
Dim G = MyColor.G
Dim B = MyColor.B

Dim HexString = String.Format("{0:X2}{1:X2}{2:X2}", R, G B)

Upvotes: 2

Hans Passant
Hans Passant

Reputation: 942538

Visual Basic is usually pretty accommodating when you try to combine numbers and text, automatically converting the number to a string to make the statement work. But the Color.R, G and B properties are a bit special, they are of type Byte. That type didn't exist in earlier versions of VB. They didn't add the automatic conversion.

Best thing to do here is to use the composite formatting feature supported by the String.Format() method:

With ColorDialog1.Color
    Label1.Text = String.Format("{0}, {1}, {2}", .R, .G, .B)
End With

And for the hex version just change the formatting string:

    Label1.Text = String.Format("#{0:x2}{1:x2}{2:x2}", .R, .G, .B)

Upvotes: 1

Related Questions