开发者

DataBinding DropDownList in C#/ASP.NET

I have a search.aspx page that has this:

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

I then have a data bind on page_load:

 StringBuilder sql = new StringBuilder();

    // Define sql
    sql.Append("SELECT pid, population ");
    sql.Append("FROM populations ");
    sql.Append("ORDER BY pid ASC ");

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

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

How do I:

  1. Add a default value/text pair to the list not in the database, like All populations?
  2. 开发者_运维技巧
  3. How do I get to do a string replace on the population data field before its shown on screen?


Add your list items to the drop down list.

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

AppendDataBoundItems will force the data items to be appended to the list that is already there. So your default item will stay.

As for doing text replacements, you can either do them in the SQL, or use DataSets/DataViews instead of straight SQL, or bind it to a list of your own objects where you can do whatever you want to do, or create a method on ItemDataBound event of the dropdown list, where you should have access to edit the information before it gets bound.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜