Wednesday, April 11, 2012

Retrieve the contents of DataSource form the ComboBox

I have a combobox that I bind with a list of objects with three properties, int a, int b, string x. When bound I set DataTextField to x and DataValue Field to a. What I want to do is get the value of b in the codebehind after the collection has been bound to the list. I do not want to use viewstate. Can I possibly use reflection? something like this?


var dataSource = ddlTest.GetDataSource();
 var newDataSource = dataSource.GetType().GetProperty("_dataSource", BindingFlags.NonPublic | BindingFlags.Instance);
 



Answer:


I'm not sure about this, but you might be able to add b as a custom attribute to the 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'd 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();
    }
}
If adding custom attributes doesn't work and you don't want to use ViewState, you might have to store both a and b in the value field, separated by a delimeter. This can be a pain because you'll have to parse the items to get the values, but given your requirements that might be the best option if the custom attributes don't work.

No comments:

Post a Comment