DropDownList的数据绑定在C#/ ASP.NET [英] DataBinding DropDownList in C#/ASP.NET

查看:412
本文介绍了DropDownList的数据绑定在C#/ ASP.NET的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有了这样的search.aspx页:

 < ASP:DropDownList的ID =ddlPopulation=服务器DataTextField =人口DataValueField =PID>
                < / ASP:DropDownList的>

然后我有一个的Page_Load绑定数据:

  StringBuilder的SQL =新的StringBuilder();    //定义SQL
    sql.Append(SELECT PID,人口);
    sql.Append(FROM人群);
    sql.Append(ORDER BY PID ASC);   IDataReader的读者= SqlHelper.GetDataReader(sql.ToString());    ddlPopulation.DataSource =阅读器;
    ddlPopulation.DataBind();

我如何:


  1. 添加默认值/文本对添加到列表不在数据库中,像所有的人群?

  2. 我要如何做一个字符串显示在屏幕上的?之前对人口数据字段替换


解决方案

添加列表项的下拉列表中。

 < ASP:DropDownList的ID =ddlPopulation=服务器DataTextField =人口DataValueField =PIDAppendDataBoundItems =真>
    < ASP:ListItem的>默认< / ASP:ListItem的>
< / ASP:DropDownList的>

AppendDataBoundItems将迫使数据项被附加到已经存在的列表中。所以,你的默认项目会留下来。

至于做文本替换,你可以做他们的SQL,或使用的DataSet / DataViews的,而不是直接的SQL,或将其绑定到自己的对象的列表,在这里你可以做任何你想做的事,或创建在下拉列表中,它得到的约束之前,你应该能够访问编辑信息的ItemDataBound事件的方法。

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. 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.

这篇关于DropDownList的数据绑定在C#/ ASP.NET的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆