0

I'm using ASP.NET to create a dynamic web form with variable controls. Some of the controls that I want to create are dropdownlists, and I would like them to be populated with certain custom subitems. How can I do this? I'm unable to populate the ddl with the subitems themselves (they are not of string type), but am also unable to populate the ddl with a string member variable (subitem.displayName) without losing the entire subitem. Here is some code for reference:

 public class SubItem
{
    string displayName;
    string value;
    ...
}

At first I tried to add the objects to the ddl directly:

DropDownList x;
x.ItemType = SubItem; //error "type not valid in this context"
x.Add(subitem); // error

Ideally, I could solve this by displaying subitem.name in the ddl, but with the functionality of a subitem being parsed, so that in an event handler I can access all of the subitem's properties. Is there something like the following that exists?

DropDownList x;
x.ItemType = SubItem;
x.DisplayType = SubItem.displayName;
x.Items.Add(subitem);

Thanks in advance!

1 Answer 1

0

You can only bind something do a DropDownList that has and IEnumerable interface. Like a List or Array.

//create a new list of SubItem
List<SubItem> SubItems = new List<SubItem>();

//add some data
SubItems.Add(new SubItem() { displayName = "Test 1", value = "1" });
SubItems.Add(new SubItem() { displayName = "Test 2", value = "2" });
SubItems.Add(new SubItem() { displayName = "Test 3", value = "3" });

//create the dropdownlist and bind the data
DropDownList x = new DropDownList();
x.DataSource = SubItems;
x.DataValueField = "value";
x.DataTextField = "displayName";
x.DataBind();

//put the dropdownlist on the page
PlaceHolder1.Controls.Add(x);

With the class

public class SubItem
{
    public string value { get; set; }
    public string displayName { get; set; }
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks! If i wanted to iterate through the dropdown list later and access the objects, would that be possible? When I try, it says "listItems cannot be converted to SubItem"
No you cant. It becomes a ListItem object. You have to create a new SubItem with the SelectedValue of the DDL.

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.