2008-09-25 1 views

ответ

0

Единственный способ сделать это - обработать событие Databinding DropDownList, вызвать метод и установить значения в элементе DropDownList самостоятельно.

-4

Декларативно:

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

Вышеприведенные связывается метод, который возвращает общий список, но вы можете также связать с методом, который возвращает DataReader. Вы также можете создать свой источник данных в коде.

+1

В вашем образце DataTextField и DataValueField являются свойствами. Мне нужен был результат вызова метода в источнике как текст или значение. – kenstone 2008-09-25 18:04:32

3

Это мое решение:

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

Иногда мне нужно использовать свойство навигации как DataTextField, как («User.Address.Description»), поэтому я решил создать простой элемент управления, производные от DropDownList. Я также внедрил EventDataBound Event, которое также может помочь.

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

Вот 2 примера для связывания выпадающего списка в ASP.net из класса

Вашей страницы ASPX

<asp:DropDownList ID="DropDownListJour1" runat="server"> 
    </asp:DropDownList> 
    <br /> 
    <asp:DropDownList ID="DropDownListJour2" runat="server"> 
    </asp:DropDownList> 

Вашего 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();  
    } 

Вашего Jour. cs class (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; 
    } 
} 
+0

Очень полезно, один из немногих ответов, которые я мог найти, которые показывают, как установить DataTextField & DataValueField – 2016-06-30 07:35:13