Extract DataSource Content from ComboBox

I have a combobox, which I tied to a list of objects with three properties: int a, int band string x. When snapping, set DataTextFieldto xand DataValueFieldto a. What I want to do is get the value bin the code after the collection has been bound to the list. I do not want to use ViewState. Can i use reflection? Something like that?

var dataSource = ddlTest.GetDataSource();
var newDataSource = dataSource.GetType().GetProperty("_dataSource", 
    BindingFlags.NonPublic | BindingFlags.Instance);
+3
source share
2 answers

I'm not sure about this, but you can add bas a custom attribute to ListItem. Try something like this and see if it works:

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());    

If you prefer to use a regular foreach loop:

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 , . , , , , .

+1

, . , , :

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

This is after I set the data source similar to this to Page_Init:

var data = new List<MyClass> { new MyClass() { a = 1, b = 2, x = "testing" } };
ddl.DataSource = data;
ddl.DataBind();
0
source

All Articles