Binding DropDownList to ListItemCollection and the Value not being added to the DDL

c#, drop-down-menu, html

Solution

Try doing:

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

Should also work, and it's probably better than looping through the list for no reason.

Update Found another (shorter) way of doing this:

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

By using `Items.AddRange()` instead of setting the source with `DataSource`, ASP is able to figure out that it should use the `Text` and `Value` properties.

Problem

I have this code in a business class. ``` 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; } ``` I get the table back from the dao without issue. I watch the text and values properties populate properly(+1 for some awesome illiteration?) and returned to the presentation and I bind like this ``` Helper helper = new Helper(); ListItemCollection agentList = helper.GetAllAgents(); agentList.Insert(0,""); this.ddlAgent.DataSource = agentList; this.ddlAgent.DataBind(); ``` when I make get the selected value ``` this.ddlAgent.SelectedValue ``` I would expect to see the agent id, but what I get is the text (agent name), so I tried this ``` this.ddlAgent.SelectedItem.Value ``` but I got the same results. I then took a look at the html source being generated and it looks like this ``` <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> ``` this pattern continues for all the agents. I'm hoping I'm just doing something bone headed and you can all snicker as you solve my problem :) Thanks guys. EDIT: if I do it like this ``` ListItemCollection agentList = helper.GetAllAgents(); agentList.Insert(0,""); foreach (ListItem agent in agentList) { this.ddlAgent.Items.Add(agent); } ``` it works fine.

Original source