0

I have a string that represents the value of a property of a control:

"objectControl.BackColor = Color.Black";

Is there any way to interpret and assign that value by code?

Thank you. Best regards, Fernando

2

1 Answer 1

2

You could parse the color name using a regular expression and then resolve the strong enumeration value of the same name using Enum.Parse.

I am not sure if you are using WPF or Windows Forms (or something else for that matter) so I will provide you an adaptable example using the ConsoleColor enumeration instead.

static void SetConsoleBackgroundColor(string statement)
{
    var colorName = Regex.Match(statement, "Color\\.(.+)").Groups[1].Value;
    var color = (ConsoleColor) Enum.Parse(typeof (ConsoleColor), colorName);
    Console.BackgroundColor = color;
}

static void Main()
{
    SetConsoleBackgroundColor("objectControl.BackColor = Color.Red");
    Console.WriteLine("Hello, World!");
    Console.ReadKey();
}

Update

Given that you are using Windows Forms and that Color is a structure and not an enumeration - use reflection to obtain the color property (instead of Enum.Parse).

private void Form1_Load(object sender, EventArgs e)
{
    SetBackColor("button1.BackColor = Color.Black");
}

public void SetBackColor(string statement)
{
    var controlName = Regex.Match(statement, "(.+?)\\.").Groups[1].Value;
    var colorName = Regex.Match(statement, "Color\\.(.+)").Groups[1].Value;

    // Todo: ensure that each of the aforementioned matches were successful.    

    var control = Controls.Find(controlName, true).FirstOrDefault();
    if (control == null) {
        throw new InvalidOperationException("Control X does not exist.");
    }

    var property = (Color) typeof (Color).GetProperty(colorName).GetValue(null);
    control.BackColor = property;
}
Sign up to request clarification or add additional context in comments.

3 Comments

@ByteBlastÇ Thank you. I tried this (WinForm), but an error raises: "Type provided must be an Enum."
@FernandaB. Oh balls. Color is a struct. Hold on.
@FernandaB. Updated my answer bud.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.