Binding DropDownList to ListItemCollection and value that is not added to DDL

I have this code in 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 am returning a table from dao without any problems. I observe how the properties of the text and values ​​are filled in properly (+1 for some awesome illiteracy?) And return to the presentation, and I bind it like

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

when i do getting the selected value

 this.ddlAgent.SelectedValue 

I would expect to see the agent identifier, but I get the text (agent name), so I tried this

 this.ddlAgent.SelectedItem.Value 

but I got the same results. Then I looked at the generated html source 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 template is saved for all agents. I hope that I'm just doing something bony and you can all smile when you solve my problem :)

Thanks guys.

EDIT: if I do it like

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

It works great.

+6
html c # drop-down-menu
source share
2 answers

Try to do:

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

It should also work, and this is probably better than switching through the list for no reason.

Update Find another (shorter) way to do this:

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

Using Items.AddRange() instead of setting the source using a DataSource , ASP can figure out that it should use the Text and Value properties.

+15
source share

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

 this.ddlAgent.Items.AddRange( agentList.Cast<ListItem>().ToArray() ) ; 
+6
source share

All Articles