Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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();
like image 858
cdub Avatar asked Jan 16 '26 23:01

cdub


1 Answers

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());
  }
}
like image 147
Dustin Hodges Avatar answered Jan 19 '26 16:01

Dustin Hodges



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!