[英]Retrieve the contents of DataSource from the ComboBox
我有一个组合框,我绑定到具有三个属性的对象列表: int a
, int b
和string x
。 绑定时,我将DataTextField
设置为x
,将DataValueField
为a
。 我想要做的是在将集合绑定到列表后,在代码隐藏中获取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
,并用分隔符分隔。 这可能会很麻烦,因为您必须解析项目以获取值,但如果自定义属性不起作用,则可能是最佳选择。
我认为这种方法应该有效。 但是,要获得具有反射的属性值,您必须执行以下操作:
var dataSource = ddlTest.DataSource;
PropertyInfo property = dataSource.GetType().GetProperty("b", BindingFlags.NonPublic | BindingFlags.Instance);
var bValue = property.GetValue(dataSource, null);
编辑我认为问题是我们没有考虑数据源是数组/列表的事实。 我按照以下方式工作:
var data = (IEnumerable<object>)ddlTest.DataSource;
Type t = typeof(MyClass);
var item = data.ToArray()[0];
System.Reflection.PropertyInfo pi = t.GetProperty("b");
int val = (int)pi.GetValue(item, null);
这是在我在Page_Init中设置这样的数据源之后:
var data = new List<MyClass> { new MyClass() { a = 1, b = 2, x = "testing" } };
ddl.DataSource = data;
ddl.DataBind();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.