Search code examples
vb.netformattingbackcolor

vb.net - set form background color programatically from a string variable


I've got a string that contains an RGB value, so like "224,224,224". I'm trying to use that value to set the background color of a form, but its erroring out and I'm not sure why.

I'm trying...

 If Not this_dialog_backcolor = "" Then _
     new_dialog.BackColor = Color.FromArgb(this_dialog_backcolor)

I get the exception

control does not support transparent background colors.

I tried amending the string to contain a 4th value, so it became "255,224,224,224" and this also errored, giving the exception that the arithmatic operation resulted in an overload.

I also tried having the string formatted like so:

 Color [A=255, R=33, G=33, B=33]

This time i get the exception 'Conversion from string 'Color [A=255, R=33, G=33, B=33]' to type integer is not valid.

Any help appriciated.


Solution

  • FromArgb is a method that doesn't accept a string as parameter. So an automatic conversion happens here and you cannot be sure that this conversion do what you need to do.
    If you had Option Strict On this error would have been catched at compile time.

    You can approach your problem in a different way, for example, you could split the string in its subparts and then call the FromArgb using the proper color values

    Dim s As String = "224,224,224"
    
    if Not string.IsNullOrEmpty(s) Then
        Dim p = s.Split(","c).Select(Function(x) int32.Parse(x.Trim()))
        form1.BackColor = Color.FromArgb(p(0),p(1),p(2))
    End If