简体   繁体   English

C#/ASP.NET 中的数据绑定下拉列表

[英]DataBinding DropDownList in C#/ASP.NET

I have a search.aspx page that has this:我有一个 search.aspx 页面,其中包含:

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

I then have a data bind on page_load:然后我在 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. 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. AppendDataBoundItems 将强制将数据项附加到已经存在的列表中。 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.至于进行文本替换,您可以在 SQL 中进行,或者使用 DataSets/DataViews 而不是直接的 SQL,或者将其绑定到您自己的对象列表中,您可以在其中做任何您想做的事情,或者在下拉列表的 ItemDataBound 事件,您应该有权在绑定之前编辑信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM