Add fields dynamically at runtime based on user input in C #

In C #, how would I best deal with this scenario, the form contains a large number of 100+ checkboxes that map to columns / fields in the datastore and the user can select any of them. Depending on which ones they choose when submitting the form, I will generate a csv data output but only showing the fields (columns) they 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 it at runtime to decide which fields will be added above, but I wanted to avoid 100+ if the blocks decide when the weather will add data.

I've looked at dynamic and expando objects, but I'm not sure if this helps in this scenario.

Any views are appreciated.

+3


source to share


2 answers


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

      



This will save the ListItems that were checked, assuming you are using CheckBoxList

. From there, you can iterate through the selected list and convert the entries to the correct csv format.

0


source


Give the name of the labels the same as you have in the mydata list. Scroll through the list and find your checkboxes using the findControl () function to set the Boolean value checkbox. Add it to the list.



0


source







All Articles