如何更改ASP.NET中DropDownList中的项目

时间:2011-08-15 22:47:15

标签: c# asp.net databound

我有这个在我的代码背后绑定:

 <asp:DropDownList id="ddlPopulation" runat="server" DataTextField="population" DataValueField="pid" AppendDataBoundItems="True">
<asp:ListItem>Default</asp:ListItem>

如何更改后面代码中的列表项?我想在它们呈现给用户之前做一个Html_Decode并修剪它们吗?

DataBind代码是:

 StringBuilder sql = new StringBuilder();

    // Define sql
    sql.Append("SELECT DISTINCT datasource ");
    sql.Append("FROM meta ");
    sql.Append("WHERE datasource != '' ");
    sql.Append("ORDER BY datasource ASC ");

    IDataReader reader = SqlHelper.GetDataReader(sql.ToString());

    ddlDatasources.DataSource = reader;
    ddlDatasources.DataBind();

1 个答案:

答案 0 :(得分:7)

您可以订阅DropDownList的DataBound事件,并执行以下操作:

<asp:DropDownList id="ddlPopulation" runat="server" DataTextField="population" DataValueField="pid" AppendDataBoundItems="True" OnDataBound="ddlPopulation_DataBound">
    </asp:DropDownList>

protected void ddlPopulation_DataBound(object sender, EventArgs e) {
  foreach(ListItem Item in ddlPopulation.Items){
    Item.Text = Server.HtmlDecode(Item.Text.Trim());
  }
}