3

I am trying to find a way to loop through the properties of an EF object and update the values of these properties. More specifically I have 50 fields that are populated by up to 50 dropdownlists. All 50 may or may not need to be populated.

To solve this I have a repeater that will create up to 50 DDL. The user will select the values for each one and then press an update button. I am looping through the items in the repeater and can keep count of which iteration I am on in the repeater. I want to also use this count to know what field I need to update. For instance DDL1 = FIELD1, DDL2 = FIELD2, ....).

Here is an example of what I am trying to do:

using (Data.Entities dataContext = new Data.Entities)
{
    var efObject = dataContext.EFData.Where(c => c.ID = [SOMEID]).First();

    int posCount = 0;
    foreach (RepeaterItem rep1 in repeaterControl.Items)
    {
        DropDownList ddlControl= (DropDownList)rep1.FindControl("ddlControl");

        //Here is where I need to update a field
        //Something like:  efObject.Field# = ddlControl.SelectedValue;
    }
}

Is there any way to dynamically create the property name I need to update?

Is there some property collection I can access by index?

Is this even remotely close to how I should be going about this?

Any and all help will be much appreciated. Thank you.

1 Answer 1

11

You could do something like this.

var properties = typeof(EFType).GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (var property in properties)
{
    var control = (DropDownList)rep1.FindControl("ddlControl" + property.Name);
    property.SetValue(efObject, control.SelectedValue, null);
}

SelectedValue is string. So you need to take care of type conversion if needed.

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

1 Comment

Perfect. This is exactly what I needed. Just 1 note, had to add a null value for the 3rd parameter to the SetValue method.

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.