简体   繁体   中英

ASP.NET web control drop down list object population

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!

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; }
}

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