开发者

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

开发者 https://www.devze.com 2022-12-18 16:17 出处:网络
I have this code in a business class. internal ListItemCollection GetAllAgents() { DataTable table = dao.GetAllAgents();

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开发者_JS百科 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.


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.


If agentList is a ListItemCollection the following code works for me, without calling this.ddlAgent.DataBind();

this.ddlAgent.Items.AddRange( agentList.Cast<ListItem>().ToArray() ) ;
0

精彩评论

暂无评论...
验证码 换一张
取 消