Fernanda B.
Fernanda B.

Reputation: 13

Dynamically run "string" in c#

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

Upvotes: 0

Views: 106

Answers (1)

User 12345678
User 12345678

Reputation: 7804

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;
}

Upvotes: 2

Related Questions