2010-01-29 11 views
6

Tengo este código en una clase ejecutiva.Enlazar DropDownList a ListItemCollection y no agregar el valor al 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; 
    } 

Obtengo la tabla de regreso del dao sin problema. Miro el texto y los valores de las propiedades pueblan correctamente (1 por alguna illiteration impresionante?) Y regresó a la presentación y Ato como esto

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

cuando hago obtener el valor seleccionado

this.ddlAgent.SelectedValue 

I esperaríamos ver el ID de agente, pero lo que se ve es el texto (nombre comercial), así que probé este

this.ddlAgent.SelectedItem.Value 

pero me dio los mismos resultados. Luego tomó un vistazo a la fuente HTML que se genera y parece que este

<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> 

este patrón continúa para todos los agentes. Espero que esté haciendo algo con cabeza de hueso y todos pueden reírse mientras resuelven mi problema :)

Gracias chicos.

EDIT: si lo hago como esto

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

que trabaja muy bien.

Respuesta

15

trate de hacer:

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

también debería funcionar, y es probable que sea mejor que el bucle a través de la lista sin ninguna razón.

actualización encontrado otra manera (más corto) de hacer esto:

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

Mediante el uso de Items.AddRange() en lugar de establecer la fuente con DataSource, ASP es capaz de averiguar que debería utilizar el Text y Value propiedades .

+0

que es el billete ... Me pregunto por qué iban a hacerlo de esta manera? – jim

+0

Debe especificar qué campos debe usar DropDownList como texto y valor. Parece que se haría automáticamente (con los parámetros para crear un nuevo ListItem que también se llama valor y texto) pero tiene que ser explícito. – Farinha

+0

gracias por eliminar el misterio – jim

6

Si agentList es ListItemCollection el siguiente código funciona para mí, sin llamar a this.ddlAgent.DataBind();

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