How do I alter the items in my DropDownList in ASP.NET

cdub picture cdub · Aug 16, 2011 · Viewed 9.5k times · Source

I have this that gets bound in my code behind:

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

How do I alter the list items in the code behind? I want to do an Html_Decode and Trim on them before they are rendered to the user?

The DataBind code is:

 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();

Answer

Dustin Hodges picture Dustin Hodges · Aug 16, 2011

You can subscribe to the DataBound event of the DropDownList and do something like the following:

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

and

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