views:

1939

answers:

3

Is there anyway to have items in an ASP.NET DropDownList have either their Text or Value bound to a method on the source rather than a property?

+1  A: 

The only way to do it is to handle the Databinding event of the DropDownList, call the method and set the values in the DropDownList item yourself.

Joseph Daigle
A: 

Declaratively:

<asp:DropDownList ID="ddlType" runat="server" Width="250px" AppendDataBoundItems="true" DataSourceID="dsTypeList" DataTextField="Description" DataValueField="ID">
    <asp:ListItem Value="0">All Categories</asp:ListItem>
</asp:DropDownList><br />
<asp:ObjectDataSource ID="dsTypeList" runat="server" DataObjectTypeName="MyType" SelectMethod="GetList" TypeName="MyTypeManager">
</asp:ObjectDataSource>

The above binds to a method that returns a generic list, but you could also bind to a method that returns a DataReader. You could also create your dataSource in code.

HectorMac
In your sample, DataTextField and DataValueField are properties. I needed the result of calling a method on the source to be the text or value.
kenstone
+1  A: 

This is my solution:

<asp:DropDownList ID="dropDownList" runat="server" DataSourceID="dataSource" DataValueField="DataValueField" DataTextField="DataTextField" />
<asp:ObjectDataSource ID="dataSource" runat="server" SelectMethod="SelectForDataSource" TypeName="CategoryDao" />

public IEnumerable<object> SelectForDataSource()
{
    return _repository.Search().Select(x => new{
        DataValueField = x.CategoryId, 
        DataTextField = x.ToString() // Here is the trick!
    }).Cast<object>();
}
Gian Marco Gherardi