博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

DropDownList的几种绑定数据方法

Posted on 2008-11-11 08:50  Sunny Xu  阅读(849)  评论(0编辑  收藏  举报

在写页面时经常用到DropDownList,当它的数据源类型不同时,我们应该选择不同的绑定方法,尽量避免错误。

  1. 当数据源是NoticeTexts时可以这样:

  var expertNation = Database.NoticeTexts.GetNoticeTexts(NoticeTextType.Nation);//获取Nation

  expertNation.Insert(0, new NoticeText { Value = "请选择民族".Trim() });//在原有数据源的基础上加上一项
  expertNation.ApplyToListControl(DropDownListExpertNation, expert.Nation);//绑定

   2.   数据源是枚举类型:

   页面直接绑定:              

                           <td class="data">
                                <asp:DropDownList ID="DropDownListEpertState" Width="155px" runat="server">
                                    <asp:ListItem Text="在职" Value="1"></asp:ListItem>
                                    <asp:ListItem Text="出国" Value="2"></asp:ListItem>
                                    <asp:ListItem Text="非在职" Value="3"></asp:ListItem>
                                </asp:DropDownList>
                            </td>

   3.数据库中直接获取(一般情况用这种方法比较安全,可以避免一些奇怪的bug):

    var expertCollege = Database.Departments.GetCollege();

    DropDownListExpertCollege.Items.Add(new ListItem { Text = "请选择所在学院", Value = "请选择所在学院", Selected = ! expert.CollegeID.HasValue });
    foreach (var college in expertCollege)
       DropDownListExpertCollege.Items.Add(new ListItem { Text = college.Name, Value = college.ID.ToString(), Selected = expert.CollegeID.HasValue && expert.CollegeID.Value == college.ID }); 

暂时学到这些,如有新的方法,再续。