1

To make this easier, I will show my code and then explain what im trying to do.

CODE+EXPLANATION:
First, when the user clicks on a button it goes to Other with additonal information.

private void button1_Click(object sender, EventArgs e)
    => Other("https://pastebin.com/raw/something", "Program1", "A");

private void button2_Click(object sender, EventArgs e)
    => Other("https://pastebin.com/raw/something", "Program2", "B");

Second, I download an XML document and extract neccesary information from it:

private void Other(string UniversalURL, string ProductNAME, string ProductCHANNEL)
    {
        //Download the Doc

        XmlDocument document = new XmlDocument();
        document.Load(UniversalURL);
        string expandedEnvString = Environment.ExpandEnvironmentVariables("%USERPROFILE%/AppData/Local/Temp/zADU.xml");
        File.WriteAllText(expandedEnvString, document.InnerXml);
        XmlDocument doc = new XmlDocument();
        doc.Load(expandedEnvString);

        //Get the needed Nodes

        XmlNode nodeXMLProgram = doc.DocumentElement.SelectSingleNode($"/{ProductNAME}");
        string XMLProgram = nodeXMLProgram.InnerText;

        // Creation of Button Here
    }

GOAL: What I want to be able to do is use the strings, extracted from the XML and use them as variables in the creation of button, Kind of like this:

Button Program(XMLProgram) = new Button();
Program(XMLProgram).Height = 22;
Program(XMLProgram).Width = 122;
Program(XMLProgram).BackColor = Color.FromArgb(230, 230, 230);
Program(XMLProgram).ForeColor = Color.Black;
Program(XMLProgram).Name = "DynamicButton";
Program(XMLProgram).Click += new EventHandler(ProgramProgram(XMLProgram)_Click);
Program(XMLProgram).BringToFront();
Controls.Add(ProgramProgram(XMLProgram));

Would I be able to do this? Help would be appreciated! Sorry for confusing title, I don't know how to phrase it properly.

4
  • What are you trying to achieve? A "dynamic" winform gui that get its properties from outside during its execution? Commented May 10, 2019 at 3:44
  • the answer to is this possible? is yes. just do some research for data driven control creation. hard to tell from your post but I'm assuming this is winforms? Commented May 10, 2019 at 3:55
  • Yes, maybe take a look at this:support.microsoft.com/en-us/help/319266/… or this if it's WPF stackoverflow.com/questions/4990624/… Commented May 10, 2019 at 3:58
  • Ted Zhang, I know how to add controls, I want to learn how to use a variable when creating those controls. Commented May 10, 2019 at 4:07

1 Answer 1

0

You can use Reflection to look for and set the properties of the object you are deserializing automatically, provided you have a properly formatted XML file.

Read your XML file through XDocument or XmlDocument, extract from it the type of control you need to create (button, textbox, etc), also extract the property names to set from the XML, and the values to set them to. Then create an instance of said control type, and use code like this to go through your property list from the XML and set them in your instance:

        // New instance of the control (read the type from the XML and create accordingly)
        var ctrlInstance = new Button();

        // Get a reference to the type of the control created.
        var ctrlType = ctrlInstance.GetType();

        // Dictionary to contain property names and values to set (read from XML)
        var properties = new Dictionary<string, object>();

        foreach (var xmlProp in properties)
        {
            // Get a reference to the actual property in the type
            var prop = ctrlType.GetProperty(xmlProp.Key);
            if (prop != null && prop.CanWrite)
            {
                // If the property is writable set its value on the instance you created
                // Note that you have to make sure the value is of the correct type
                prop.SetValue(ctrlInstance, xmlProp.Value, null);
            }
        }

If you intend to create an entire program this way, including code, you will have to use Roslyn to compile your code at runtime, which can be somewhat complicated to put into practice. In that case, you don't need an XML file, you just need to put put all your code into a source file and compile it, then instantiate it in your own program. If you just want to create a form programmatically and handle events in its parent form, this will work fine.

Sign up to request clarification or add additional context in comments.

1 Comment

Perfect! Thank you! I have 10 buttons so I could copy and paste the old script, but I was wondering if their would be a better solution.

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.