views:

401

answers:

1

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.

+1  A: 

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.

Farinha
that's the ticket...I wonder why they would do it this way?
jim
You need to specify which fields should the DropDownList use as text and value. It does look like it would be done automatically (with the parameters to create a new ListItem also being called value and text) but it has to be explicit.
Farinha
thanks for removing the mystery
jim