简体   繁体   中英

append fields dynamically at runtime based on user input in c#

In c# how would I best handle this scenario, a form contains a large number of checkboxes 100+ which map to columns/fields in the data store, and the user can select any of them. Depending on those they choose when they submit the form I will generate a csv output of the data but only showing the fields(columns) they have requested.

list myData = getAllTheData
var fieldstheychose = "name, mileage, address"

            foreach (var item in mydata)
                {
                var somedata = new StringBuilder();

                // make decision to include field or not
                somedata.Append(item.name.formatvalue() + ",");
                // make decision to include field or not
                somedata.Append(item.mileage.GetCSVEncodedValue() + ",");
                // make decision to include field or not
                somedata.Append(item.address.ToDisplayString() + ",");

                // make decision on 100+ fields that might be in the fieldstheychose list depending on their choices
        }
    return somedata;

I need to at runtime decide which fields will be appended above but I wanted to avoid 100+ if blocks to decide weather to append the data.

I did look at dynamic objects and expando objects but I'm not sure it helps in this scenario.

Any views appreciated.

List<ListItem> selected = new List<ListItem>();
foreach (ListItem item in YourCheckBoxListID)
    if (item.Selected) 
        selected.Add(item);

This will store the ListItems that have been checked assuming you are using a CheckBoxList . From there you can iterate through your selected list and convert the entries into proper csv format.

Give the name of the checkboxes same to what you have in the list mydata. Loop through the list and find your check-boxes using the findControl() function to get the checkbox checked Boolean value. Add it to the list.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM