Results 1 to 7 of 7

Thread: [RESOLVED] convert string to color

  1. #1

    Thread Starter
    Lively Member
    Join Date
    Feb 2008
    Location
    Botswana
    Posts
    107

    Resolved [RESOLVED] convert string to color

    hey everyone, just need some help converting a string to color. i use the colordialog to the user can pick a color, which is then saved into a db. when i load the color to fill a lable it comes as a string. so, how do i convert:

    Color [A=255, R=128, G=128, B=255] to color

    also, when i use the colordialog, it will save basic colors as color[TheColor] and complex as the one above. to be uniform, is there a way to have the colordialog always return a hex value? or do i need to write a function for that?

    thanks
    jason
    I am using Microsoft Visual Basic 2008 Express Edition. I use Access for my data base

  2. #2
    VB Addict Pradeep1210's Avatar
    Join Date
    Apr 2004
    Location
    Inside the CPU...
    Posts
    6,614

    Re: convert string to color

    Use the FromName, FromArgb or FromKnownColor method of the Color class.

    vb.net Code:
    1. Dim c As Color
    2.  
    3. 'if you know the common name
    4. c = Color.FromName("red")
    5.  
    6. 'if you know the color numeric values
    7. c = Color.FromArgb(255, 255, 255)       'red, green, blue: see other overloads too for more options
    8.  
    9. 'if you know the knowncolor name
    10. c = Color.FromKnownColor(KnownColor.Red)

    Also have a look at ToArgb, ToKnownColor, ToString methods for inverse of this.


    Pradeep
    Last edited by Pradeep1210; Dec 19th, 2008 at 04:04 AM.
    Pradeep, Microsoft MVP (Visual Basic)
    Please appreciate posts that have helped you by clicking icon on the left of the post.
    "A problem well stated is a problem half solved." — Charles F. Kettering

    Read articles on My Blog101 LINQ SamplesJSON ValidatorXML Schema Validator"How Do I" videos on MSDNVB.NET and C# ComparisonGood Coding PracticesVBForums Reputation SaverString EnumSuper Simple Tetris Game


    (2010-2013)
    NB: I do not answer coding questions via PM. If you want my help, then make a post and PM me it's link. If I can help, trust me I will...

  3. #3
    Raging swede Atheist's Avatar
    Join Date
    Aug 2005
    Location
    Sweden
    Posts
    8,018

    Re: convert string to color

    I'd advice you to use the System.Drawing.ColorTranslator.ToHtml method on the color to get a string with the HTML string representation of it, and save that to the database instead.
    When you get the string from the database later, use the System.Drawing.ColorTranslator.FromHtml to make it into a Color again
    Rate posts that helped you. I do not reply to PM's with coding questions.
    How to Get Your Questions Answered
    Current project: tunaOS
    Me on.. BitBucket, Google Code, Github (pretty empty)

  4. #4
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,221

    Re: convert string to color

    Quote Originally Posted by Atheist
    I'd advice you to use the System.Drawing.ColorTranslator.ToHtml method on the color to get a string with the HTML string representation of it, and save that to the database instead.
    When you get the string from the database later, use the System.Drawing.ColorTranslator.FromHtml to make it into a Color again
    I'd be more inclined to save an Integer to the database and use Color.ToArgb and Color.FromArgb unless there's a reason to go into the database and edit the values, which would be easier with the string.
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

  5. #5
    PowerPoster Deepak Sakpal's Avatar
    Join Date
    Mar 2002
    Location
    Mumbai, India
    Posts
    2,424

    Re: convert string to color

    Better you store the 32-bit ARGB value. It's basically a numeric value. If you code this way then there won't be any need to write a function to extract the color value. Here is some piece of code:

    vb.net Code:
    1. Public Class Form1
    2.  
    3.     Private Sub Button1_Click( _
    4.         ByVal sender As System.Object, _
    5.         ByVal e As System.EventArgs _
    6.     ) Handles Button1.Click
    7.  
    8.         Dim clrDialog As New ColorDialog
    9.         If clrDialog.ShowDialog = Windows.Forms.DialogResult.OK Then
    10.             TextBox1.Text = clrDialog.Color.ToArgb.ToString ' Store this value in DB.
    11.         End If
    12.         clrDialog.Dispose()
    13.     End Sub
    14.  
    15.     Private Sub Button2_Click( _
    16.         ByVal sender As System.Object, _
    17.         ByVal e As System.EventArgs _
    18.     ) Handles Button2.Click
    19.  
    20.         ' Get the ARGB value from DB and use it.
    21.         TextBox1.BackColor = Color.FromArgb(CInt(TextBox1.Text))
    22.     End Sub
    23.  
    24. End Class

    EDIT: Damn.... When I started reply, there were no replies and now three replies already posted. Am I that much slow

  6. #6

    Thread Starter
    Lively Member
    Join Date
    Feb 2008
    Location
    Botswana
    Posts
    107

    Re: convert string to color

    thanks everyone.
    I am using Microsoft Visual Basic 2008 Express Edition. I use Access for my data base

  7. #7
    Addicted Member
    Join Date
    Dec 2009
    Location
    Arizona
    Posts
    185

    Re: [RESOLVED] convert string to color

    Here is some things I refactored today, it may have errors, but as far as I can tell, nothing horrible.
    I use these a lot in the application I wrote that colors text. Generics make life so easy!

    This may have some interwoven-ness with the app I built using it, i.e., you will see one instance
    were I refer to FrmMain, so beware, these are not necessarily made to work alone, but it would
    be REAL easy to make them that way. . .

    Code:
        Public Function getColorComponentsRGBValuesFromColor(ByVal clr As Color) As Stack(Of Byte)
            Dim R, G, B, A As Byte
            Dim colorStringStack As New Stack(Of String)
            Dim colorByteStack As New Stack(Of Byte)
    
            Try
                colorStringStack = getColorARGBValuesFromString(clr.ToString)
                If colorStringStack.Count > 0 Then
                    A = CByte(colorStringStack.Pop) ' 255 if not transparent
                    R = CByte(colorStringStack.Pop)
                    G = CByte(colorStringStack.Pop)
                    B = CByte(colorStringStack.Pop)
                Else   ' not a custom color, get color from name
                    R = clr.R
                    G = clr.G
                    B = clr.B
                    A = 255  ' defaulting to non-transparent
                End If
                colorByteStack.Push(B)
                colorByteStack.Push(G)
                colorByteStack.Push(R)
                colorByteStack.Push(A)
    
            Catch ex As Exception
                genFns.reportError("Error:" & ex.StackTrace & ". . . ." & vbCrLf & Err.Description, ex)
            End Try
            Return colorByteStack
        End Function
    
        ' used 3 times
        Public Function getColorARGBValuesFromString(ByVal ARGBStr As String) As Stack(Of String)
            Dim Astr As String = ""
            Dim Rstr As String = ""
            Dim Gstr As String = ""
            Dim Bstr As String = ""
            Dim colorList As New List(Of String)
            Dim colorStack As New Stack(Of String)
            Try
                ' check for a custom color i.e. A=255, R= 0, G=255, B=64
                ' This function first checks for a custom color, it one is present it returns TRUE
                ' then it fills the array with the color numbers for A, R, G, B
                'storedColor = "A=255, R=0, G=255, B=164"  ' for info and testing
                colorList.AddRange(Strings.Split(ARGBStr, ","))
                For Each item In colorList
                    colorStack.Push(item)
                Next
                ' colorStack holds {"B=64", "G=255", "R=0", "A=255"} is it is a custom color
                ' If it is a custom color, convert to get a color
                If colorStack.Count = 4 Then
                    Bstr = Strings.Replace(colorStack.Pop, "B=", "")
                    Gstr = Strings.Replace(colorStack.Pop, "G=", "")
                    Rstr = Strings.Replace(colorStack.Pop, "R=", "")
                    Astr = Strings.Replace(colorStack.Pop, "A=", "")
                    colorStack.Clear()
                    colorStack.Push(Bstr)
                    colorStack.Push(Gstr)
                    colorStack.Push(Rstr)
                    colorStack.Push(Astr)
                    Return colorStack
                    Exit Function
                End If
    
            Catch ex As Exception
                genFns.reportError("Error:" & ex.StackTrace & ". . . ." & vbCrLf & Err.Description, ex)
            End Try
            Return colorStack
        End Function
    
        ' get the color value of this string 
        Public Function interpretColorString(ByVal colorString As String, Optional ByVal z As Integer = -1) As Color
            Try
                Dim colorVal As Color
                Dim colorStack As New Stack(Of String)
    
                If InStr(colorString, "Color [") > 0 Then
                    colorString = Strings.Replace(colorString, "Color [", "")
                    colorString = Strings.Replace(colorString, "]", "")
                End If
    
                ' check for a custom color i.e. A=255, R= 0, G=255, B=64
                ' This function first checks for a custom color, it one is present it returns 
                ' a Stack(Of String) with the color numbers for A, R, G, B
    
                colorStack = getColorARGBValuesFromString(colorString)
                If colorStack.Count > 3 Then
                    Dim A, R, G, B As String
                    Dim Aint, Rint, Gint, Bint As Integer
                    A = colorStack.Pop
                    R = colorStack.Pop
                    G = colorStack.Pop
                    B = colorStack.Pop
                    Aint = CInt(A)
                    Rint = CInt(R)
                    Gint = CInt(G)
                    Bint = CInt(B)
                    colorVal = Color.FromArgb(Aint, Rint, Gint, Bint)
                Else
                    If colorString = "" And z > -1 Then
                        colorVal = FrmColor.colorArray(z)
                    Else
                        colorVal = Color.FromName(colorString)
                    End If
                End If
                Return colorVal
    
            Catch ex As Exception
                genFns.reportError("Error:" & ex.StackTrace & ". . . ." & vbCrLf & Err.Description, ex)
            End Try
        End Function
    Last edited by skywola; Jun 9th, 2012 at 11:05 PM.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width