简体   繁体   English

ASP.NET Web控件下拉列表对象填充

[英]ASP.NET web control drop down list object population

I'm using ASP.NET to create a dynamic web form with variable controls. 我正在使用ASP.NET创建带有可变控件的动态Web表单。 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. 我无法使用子项本身填充ddl(它们不是字符串类型),但是也无法使用字符串成员变量(subitem.displayName)填充ddl而不会丢失整个子项。 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: 首先,我尝试将对象直接添加到ddl中:

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. 理想情况下,我可以通过在ddl中显示subitem.name来解决此问题,但是要解析一个子项的功能,以便在事件处理程序中可以访问该子项的所有属性。 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. 您只能绑定具有和IEnumerable接口的DropDownList。 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; }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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