我有一个组合框,它绑定(bind)到具有三个属性的对象列表:int a
、int b
和 string x
。绑定(bind)时,我将 DataTextField
设置为 x
并将 DataValueField
设置为 a
。我想要做的是在集合绑定(bind)到列表后在代码隐藏中获取 b
的值。我不想使用 ViewState。我可以使用反射吗?是这样的吗?
var dataSource = ddlTest.GetDataSource();
var newDataSource = dataSource.GetType().GetProperty("_dataSource",
BindingFlags.NonPublic | BindingFlags.Instance);
最佳答案
我对此不确定,但您可能能够将b
作为自定义属性添加到ListItem
。尝试这样的事情,看看它是否有效:
var table = new DataTable("TableName");
//bind the dropdown to the result set
dropDownList.DataSource = table;
dropDownList.DataBind();
//iterate through the datasource and add custom attributes for each item in the list
table.AsEnumerable().ToList().ForEach(r =>
dropDownList.Items.FindByValue(r.Field<int>("a").ToString()).Attributes["data-field"] = r.Field<int>("b").ToString());
如果您更喜欢使用常规的 foreach 循环:
foreach (DataRow row in table.Rows)
{
var item = dropDownList.FindByValue(row.Field<int>("a").ToString());
if (item != null)
{
item.Attributes["data-value"] = row.Field<int>("b").ToString();
}
}
如果添加自定义属性不起作用并且您不想使用 ViewState,您可能必须将 a
和 b
存储在值字段中,分开由定界符。这可能会很痛苦,因为您必须解析项目以获取值,但考虑到您的要求,如果自定义属性不起作用,这可能是最佳选择。
关于c# - 从 ComboBox 中检索 DataSource 的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10105206/