The properties of the class WinForm_ dynamically created using Reflected Label

Class:

    class Recipe
    {
        public int ID { get; set; }
        public string RecipeName { get; set; }
        public string Comment { get; set; }
        public string Quantity { get; set; }
        public string con1 { get; set; }
        public string con2 { get; set; }
        public string con3 { get; set; }
    }

Now according to con1, con2 and con3 dynamically create three label.

            int X = 75, Y = 65, i = 0;
            Recipe recipe = new Recipe { ID = 1, con1 = "p1", con2 = "p2", con3 = "p3" };
            foreach (var prop in recipe.GetType().GetProperties())
            {
                if (prop.Name.StartsWith("con"))
                {
                    var value = prop.GetValue(recipe);
                    if (value != null)
                    {
                        Label label = new Label()
                        {
                            AutoSize = true,
                            MaximumSize = new Size(300, 150),
                            MinimumSize = new Size(300, 10),
                            Location = new Point(X, Y + 20 * i),
                            Text = value.ToString()
                        };
                        i++;
                        Controls.Add(label);
                    }
                }
            }

Test Results:

Guess you like

Origin www.cnblogs.com/xingyz/p/12612533.html