簡體   English   中英

從ComboBox中檢索DataSource的內容

[英]Retrieve the contents of DataSource from the ComboBox

我有一個組合框,我綁定到具有三個屬性的對象列表: int aint bstring x 綁定時,我將DataTextField設置為x ,將DataValueFielda 我想要做的是在將集合綁定到列表后,在代碼隱藏中獲取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,則可能必須在值字段中存儲ab ,並用分隔符分隔。 這可能會很麻煩,因為您必須解析項目以獲取值,但如果自定義屬性不起作用,則可能是最佳選擇。

我認為這種方法應該有效。 但是,要獲得具有反射的屬性值,您必須執行以下操作:

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM