Method
Method

Reputation: 143

Edit Method WPF | Dynamic Parameters

Situation

I'm trying to make an edit member method for my WPF application.

Basically, I have a list of members in my main class, I iterate through that list of members and find the member with the matching Username parameter, that works.

Then, once that username is found within the system (which it will be since the member needs to login with a valid one) I want to set the member."Whatever" paramater to whatever parameter the user chose to edit on the gui, with the new content the user has entered for that parameter.

public void editMember(string Username, string parameter, string newEntry)
        {



            foreach (BaseMember bm in members)
            {

                if (Username == bm.username)
                {
                    bm.[parameter] = newEntry;
                }
            }

Problem

I don't want to do:

"member.club" and "member.firstname", or "member.street", since there are far too many parameters that can be edited by the user, and it's long winded "bad" code.

how can I do this in ONE line of code? since bm.[parameter] = newEntry; won't work?

More info

This method works if I use a static parameter, for instance, bm.memclub = newEntry; but I want the parameter to be dynamic.

Upvotes: 2

Views: 224

Answers (1)

MRebai
MRebai

Reputation: 5474

You need to use Reflection:

      foreach (BaseMember bm in members)
        {

            if (Username == bm.username)
            {  
                Type type = bm.GetType();

                PropertyInfo prop = type.GetProperty(parameter);

                prop.SetValue (bm, newValue, null);
            }
        }

Reflection provides objects (of type Type) that describe your current object.You can use reflection to dynamically create an instance of a type, bind the type to an existing object, or get the type from an existing object and invoke its methods or access its fields and properties.

Upvotes: 1

Related Questions