mercredi 27 mars 2019

How to pass different types of property values using reflection?

Using reflection, I am populating a combobox with class types, then creating textboxes for input, based on each class' properties.

Considering that these properties return different types (string, float, int), how can I validate each type and pass them from the textbox to create instances that are passed to a listbox ? I am learning reflection and linq, so I want to do this using them.

I tried using this Dictionary:

    private void OnButton1Click(object sender, EventArgs e)
    {
        Dictionary<string, string> populatedProperties = Controls.OfType<TextBox>()
                                                              .ToDictionary(x => x.Name, x => ValidateInputType(x.Text));

        User createdUser = (User)Activator.CreateInstance(selectedType);

        foreach (PropertyInfo property in selectedType.GetProperties().Where(x => x.CanWrite))
        {
            property.SetValue(createdUser, populatedProperties[property.Name]);
        }

        listBoxUsers.Items.Add(createdUser.ToString());
    }

//I am creating textboxes using: int i = 50;

        foreach (var prop in selectedUserType.GetProperties().Where(x => x.CanWrite))
        {
            Controls.Add( new TextBox
            {
                Name = prop.Name,
                Location = new Point(150, 10 + i),
                Tag = prop
            });

            i = i + 40;
        }

//And validating:

    private string ValidateInputType(string input)
    {
        if (string.IsNullOrWhiteSpace(input))
            return "Input is null or White Space";
    }

I expect to to able to pass these various properties to the listBox.





Aucun commentaire:

Enregistrer un commentaire