¿Hay alguna forma de tener elementos en una DropDownList de ASP.NET que tengan su Texto o Valor ligado a un método en el origen en lugar de una propiedad?Vincular ASP.NET DropDownList DataTextField al método?
Respuesta
La única manera de hacerlo es manejar el evento de enlace de datos de DropDownList, llamar al método y establecer los valores en el elemento DropDownList usted mismo.
declarativa:
<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>
Los anteriores se une a un método que devuelve una lista genérica, pero también se puede unir a un método que devuelve un DataReader. También puede crear su fuente de datos en el código.
Esta es mi solución:
<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>();
}
A veces tengo que usar las propiedades de navegación como DataTextField, como ("User.Address.Description"), por lo que decidieron crear un control simple que deriva de DropDownList. También implementé un evento ItemDataBound que también me puede ayudar.
public class RTIDropDownList : DropDownList
{
public delegate void ItemDataBoundDelegate(ListItem item, object dataRow);
[Description("ItemDataBound Event")]
public event ItemDataBoundDelegate ItemDataBound;
protected override void PerformDataBinding(IEnumerable dataSource)
{
if (dataSource != null)
{
if (!AppendDataBoundItems)
this.Items.Clear();
IEnumerator e = dataSource.GetEnumerator();
while (e.MoveNext())
{
object row = e.Current;
var item = new ListItem(DataBinder.Eval(row, DataTextField, DataTextFormatString).ToString(), DataBinder.Eval(row, DataValueField).ToString());
this.Items.Add(item);
if (ItemDataBound != null) //
ItemDataBound(item, row);
}
}
}
}
Aquí hay 2 ejemplos para la unión de un desplegable en ASP.net de una clase
Su página aspx
<asp:DropDownList ID="DropDownListJour1" runat="server">
</asp:DropDownList>
<br />
<asp:DropDownList ID="DropDownListJour2" runat="server">
</asp:DropDownList>
Su página aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
//Exemple with value different same as text (dropdown)
DropDownListJour1.DataSource = jour.ListSameValueText();
DropDownListJour1.DataBind();
//Exemple with value different of text (dropdown)
DropDownListJour2.DataSource = jour.ListDifferentValueText();
DropDownListJour2.DataValueField = "Key";
DropDownListJour2.DataTextField = "Value";
DropDownListJour2.DataBind();
}
Su jour. Clase cs (jour.cs)
public class jour
{
public static string[] ListSameValueText()
{
string[] myarray = {"a","b","c","d","e"} ;
return myarray;
}
public static Dictionary<int, string> ListDifferentValueText()
{
var joursem2 = new Dictionary<int, string>();
joursem2.Add(1, "Lundi");
joursem2.Add(2, "Mardi");
joursem2.Add(3, "Mercredi");
joursem2.Add(4, "Jeudi");
joursem2.Add(5, "Vendredi");
return joursem2;
}
}
Muy útil, una de las pocas respuestas que pude encontrar que muestran cómo configurar DataTextField y DataValueField –
- 1. Asp.Net MVC DropDownList Enlace de datos
- 2. ASP.NET Editor DropdownList
- 3. Poblar ASP.NET MVC DropDownList
- 4. ASP.NET Auto Complete DropDownList
- 5. DropDownList en ASP.NET MVC 3
- 6. Asp.NET DropDownList SelectedItem.Value no cambiar
- 7. Subclase de DropDownList en ASP.NET
- 8. Delegate.CreateDelegate() y genéricos: Error al vincular al método de destino
- 9. ASP.NET MVC DropDownList Valor seleccionado Problema
- 10. enable asp.net DropDownList control utilizando jquery
- 11. ASP.net MVC elemento DropDownList preseleccionada ignorado
- 12. llenando una DropDownlist en ASP.NET MVC
- 13. ASP.NET DropDownList Evento OnSelectedIndexChanged no activado
- 14. ASP.NET DropDownList problema: SelectedItem no está cambiando
- 15. Asp.NET DropDownList restablece SelectedIndex después de PostBack
- 16. ASP.NET MVC modelo de vista y DropDownList
- 17. "onclick" atributo a ASP.NET DropDownList elemento
- 18. DropdownList de ASP.net sin elemento seleccionado
- 19. Asp.Net MVC3 - Cómo crear Dynamic DropDownList
- 20. Cómo vincular el interceptor de método al proveedor?
- 21. lista desplegable DataTextField compuesto de propiedades?
- 22. Añadir artículo a DataBound DropDownList
- 23. matriz de unión de cadena a DropDownList?
- 24. ¿Cómo agregar un RequiredFieldValidator al control DropDownList?
- 25. ASP.NET - DropDownList contiene un valor incorrecto en el Browser-Back-Button
- 26. cómo retener espacios en DropDownList - ASP.net MVC Razor ve
- 27. Agregar separadores en DropDownList
- 28. ¿La mejor manera de implementar DropDownList en ASP.NET MVC 2?
- 29. Agregue valor vacío a DropDownList en ASP.net MVC
- 30. Error SystemFontFamilies al vincular al cuadro combinado
En su ejemplo, DataTextField y DataValueField son propiedades. Necesitaba el resultado de llamar a un método en la fuente para que sea el texto o el valor. – kenstone