在写页面时经常用到DropDownList,当它的数据源类型不同时,我们应该选择不同的绑定方法,尽量避免错误。
- 当数据源是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 });
暂时学到这些,如有新的方法,再续。