I would like to use something like directcast, or ctype but this time for a string. Unfortunately, I don't know how to proceed.
Public bttkey1color, bttkey2color, bttkey3color, bttkey4color, bttkey5color,
bttkey6color, bttkey7color as string
Dim myColor As String() = IO.File.ReadAllLines(My.Application.Info.DirectoryPath ("\Color.txt"))
how can i reduce this code? I don't need to write this dozens of times.
bttkey1color = myColor(1)
bttkey2color = myColor(2)
bttkey3color = myColor(3)
bttkey4color = myColor(4)
bttkey5color = myColor(5)
bttkey6color = myColor(6)
bttkey7color = myColor(7)
CodePudding user response:
You can use the Color.FromName(String) Method.
To reduce the code, use an array of Color for the result, instead of individual variables.
' Test
Dim colorNames As String() = {"Lime", "Black", "Red"}
Dim colors As Color() = colorNames.
Select(Function(s) Color.FromName(s)).ToArray()
For Each c In colors
Console.WriteLine(c)
Next
Prints
Color [Lime]
Color [Black]
Color [Red]
Or, if you are not comfortable with LINQ, here a solution using For-loops
Dim colorNames As String() = {"Lime", "Black", "Red"}
Dim colors(colorNames.Length - 1) As Color
For i = 0 To colorNames.Length - 1
colors(i) = Color.FromName(colorNames(i))
Next
For Each c In colors
Console.WriteLine(c)
Next
See also
- Arrays in Visual Basic
- Collections (Visual Basic) (as an alternative to arrays)
