2010-01-29 85 views
6

我在業務類中擁有此代碼。將DropDownList綁定到ListItemCollection並將值添加到DDL中

internal ListItemCollection GetAllAgents() 
    { 
     DataTable table = dao.GetAllAgents(); 
     ListItemCollection list = new ListItemCollection(); 

     foreach (DataRow row in table.Rows) 
     { 
      list.Add(new ListItem(row["agent_name"].ToString(), row["id"].ToString())); 
     } 
     return list; 
    } 

我從dao沒有問題的表回來。我看的文本和值屬性填充正確(+1一些真棒illiteration?),並返回到演示文稿,並結合我這樣

Helper helper = new Helper(); 
ListItemCollection agentList = helper.GetAllAgents(); 
agentList.Insert(0,""); 
this.ddlAgent.DataSource = agentList; 
this.ddlAgent.DataBind(); 

當我提出讓所選擇的值

this.ddlAgent.SelectedValue 

我希望看到代理ID,但我得到的是文本(代理名稱),所以我想這個

this.ddlAgent.SelectedItem.Value 

,但我得到了相同的結果。然後我看了一下生成的html源代碼,它看起來像這樣

<select name="ctl00$ContentPlaceHolder1$ddlAgent" onchange="javascript:setTimeout('__doPostBack(\'ctl00$ContentPlaceHolder1$ddlAgent\',\'\')', 0)" id="ctl00_ContentPlaceHolder1_ddlAgent"> 
     <option selected="selected" value=""></option> 
     <option value="agent1_name">agent1_name</option> 
     <option value="agent2_name">agent2_name</option> 

這種模式繼續爲所有的代理。我希望我只是做一些骨頭,當你解決我的問題時,你可以全部竊笑:)

謝謝你們。

編輯:,如果我不喜歡這樣

ListItemCollection agentList = helper.GetAllAgents(); 
agentList.Insert(0,""); 
foreach (ListItem agent in agentList) 
{ 
    this.ddlAgent.Items.Add(agent); 
} 

它工作正常。

回答

15

嘗試做:

this.ddlAgent.DataTextField = "Text"; 
this.ddlAgent.DataValueField = "Value"; 
this.ddlAgent.DataSource = agentList; 
this.ddlAgent.DataBind(); 

也應該工作,而且它可能不是通過列表無故循環更好。

更新發現這樣做的另一個(短)的方式:

this.ddlAgent.Items.AddRange(agentList.ToArray()); 
this.ddlAgent.DataBind(); 

通過使用Items.AddRange(),而不是設置與DataSource源,ASP能夠弄清楚,它應該使用TextValue性質。

+0

這就是機票...我想知道他們爲什麼要這樣做? – jim 2010-01-29 10:39:28

+0

您需要指定DropDownList應將哪些字段用作文本和值。它看起來會自動完成(使用參數來創建一個新的ListItem也被稱爲值和文本),但它必須是明確的。 – Farinha 2010-01-29 10:58:03

+0

感謝您消除這個謎團 – jim 2010-01-29 11:11:22

6

如果agentList是一個ListItemCollection,下面的代碼適用於我,而不調用this.ddlAgent.DataBind();

this.ddlAgent.Items.AddRange(agentList.Cast<ListItem>().ToArray()) ; 
相關問題