2

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();
cdub
  • 24,555
  • 57
  • 174
  • 303
  • What's with the kooky stringbuilder usage? You're not gaining anything there, you should just use a string and not concatenate? – jim Aug 15 '11 at 23:06

1 Answers1

9

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());
  }
}
Dustin Hodges
  • 4,110
  • 3
  • 26
  • 41