AppendDataBoundItems实现追加绑定

当对一个列表控件执行DataBind()会清空之前的所有数据项,因为很多时候如果加一个特殊项的话会选择在绑定完成后动态插入一条,就像下面这样

//下面前台代码 
 <asp:DropDownList ID="ddlCity" runat="server">
<asp:ListItem Text="全部" Value="0"  Selected="True"></asp:ListItem> </asp:DropDownList> //下面后台代码 Dictionary<string, string> citys = new Dictionary<string, string>(); citys.Add("北京", "1"); citys.Add("上海", "2"); ddlCity.DataSource = citys; ddlCity.DataTextField = "Key"; ddlCity.DataValueField = "Value"; ddlCity.DataBind(); ddlCity.Items.Insert(0, new ListItem("全部", "0"));

现在有了AppendDataBoundItems属性,表示是否追加绑定项,默认为false表示不追加,我们改为true就不需要像上面那样的写法了

//下面前台代码 
 <asp:DropDownList ID="ddlCity" runat="server">
 <asp:ListItem Text="全部" Value="0"  Selected="True"></asp:ListItem>
 </asp:DropDownList>
//下面后台代码
 Dictionary<string, string> citys = new Dictionary<string, string>();
 citys.Add("北京", "1");
 citys.Add("上海", "2");
 ddlCity.AppendDataBoundItems = true;//加入这个设置
 ddlCity.DataSource = citys;
 ddlCity.DataTextField = "Key";           
 ddlCity.DataValueField = "Value";
 ddlCity.DataBind();

而且如果多次调用DataBind()方法,也只会在后面追加数据而已,不管前面绑定过什么数据了,哈哈,不错吧

 

posted @ 2013-04-12 21:46  自由小菜园  阅读(1467)  评论(0编辑  收藏  举报