代码之家  ›  专栏  ›  技术社区  ›  jim

将DropDownList绑定到ListItemCollection,并且该值未添加到DDL

  •  6
  • jim  · 技术社区  · 16 年前

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

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

    当我做出选择时,获取所选的值

    this.ddlAgent.SelectedValue
    

    this.ddlAgent.SelectedItem.Value
    

    但我得到了同样的结果。然后我看了一下正在生成的html源代码,它是这样的

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

    这种模式适用于所有代理。我希望我只是在做一些愚蠢的事情,你们可以在解决我的问题时窃笑:)

    谢谢各位。

    编辑: 如果我这样做

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

    它很好用。

    2 回复  |  直到 16 年前
        1
  •  17
  •   Farinha    14 年前

    试着做:

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

    也应该有效,这可能比毫无理由地循环浏览列表要好。

    更新 找到了另一种(较短的)方法:

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

    利用 Items.AddRange() 而不是将源设置为 DataSource ,ASP能够计算出它应该使用 Text 和 Value 财产。

        2
  •  6
  •   redwud    13 年前

    如果agentList是ListItemCollection,则以下代码对我有效,无需调用this.ddlAgent.DataBind();

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