简体   繁体   中英

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.

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

You can use the ColorConverter from the namespace System.Drawing .

Dim converter = New ColorConverter()
Dim color = DirectCast(converter.ConvertFromString("255,224,224"), Color)

It can also convert colors given as web color name like "PaleVioletRed" and in hex format like "#FF0D60" .

So I've managed to achieve what i was after, but I'm not sure on its efficiency... it feels a bit dirty...

 If custom_color_scheme = true Then
 Dim back_color_bits() As String = this_dialog_backcolor.Replace(" ", "").Split(",")
 If Not this_dialog_backcolor = "" Then
     new_dialog.BackColor = Color.FromArgb(Convert.ToInt32(back_color_bits(0)), _
         Convert.ToInt32(back_color_bits(1)), Convert.ToInt32(back_color_bits(2)))
 End If

Like i said, it works, but i'm sure there must be a cleaner way. anybody?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM