技术开发 频道

ASP.NET 2.0中的数据操作:定制数据修改界面

四、用RadioButton表示Discontinued状态

Product的Discontinued字段以CheckBox列呈现,只读模式是disabled的,只有编辑模式下才被enable。根据配套需要,我们可以使用模板列对其进行定制。本节教程中,我们将使用含有RadioButtonList控件的模板列代替原来的CheckBox列,并带有两个选项-“Active” 和 “Discontinued” – 让用户选择product的Discontinued值。

先将Discontinued的CheckBox列转为模板列,会用到ItemTemplate 和 EditItemTemplate两个模板。它们使用CheckBox并将通过Checked属性绑定Discontinued字段,唯一的区别在于ItemTemplate模板中的CheckBox的Enabled属性是false。

使用RadioButtonList控件替换掉原来ItemTemplate 和 EditItemTemplate模板中的CheckBox控件,并将它们的ID属性都设置为DiscontinuedChoice。然后,设置RadioButtonLists的两个单选按钮项,一个为“Active”标签,值为“False”,另一个为“Discontinued”标签,值为“True”。这些操作即可直接在元素标记中添加<asp:ListItem>元素,也可通过设计器中ListItem集合编辑器处理。图13演示了指定两个单选按钮后的ListItem集合编辑器。


图13:为RadioButtonList增加Active和Discontinued选项

由于普通项模板ItemTemplate中的RadioButtonList不应是编辑状态,所以设置Enabled属性为false,而编辑状态对应的EditItemTemplate模板中RadioButtonList的Enabled属性则应设置为true。这样以来,非编辑行中单选按钮作为只读显示,而编辑状态则允许用户进行选择。

仍然需要用数据库中product的Discontinued数据绑定RadioButtonList控件的SelectedValue属性。像本节教程前面那样,即可直接添加绑定语法也可通过RadioButtonList的智能标记中的‘编辑DataBinding’链接。

增加完这两个RadioButtonList并做适当配置后,Discontinued的模板列元素标记大致如下:

<asp:TemplateField HeaderText="Discontinued" SortExpression="Discontinued"> <ItemTemplate> <asp:RadioButtonList ID="DiscontinuedChoice" runat="server"
Enabled
="False" SelectedValue='<%# Bind("Discontinued") %>'> <asp:ListItem Value="False">Active</asp:ListItem> <asp:ListItem Value="True">Discontinued</asp:ListItem> </asp:RadioButtonList> </ItemTemplate> <EditItemTemplate> <asp:RadioButtonList ID="DiscontinuedChoice" runat="server"
SelectedValue
='<%# Bind("Discontinued") %>'> <asp:ListItem Value="False">Active</asp:ListItem> <asp:ListItem Value="True">Discontinued</asp:ListItem> </asp:RadioButtonList> </EditItemTemplate> </asp:TemplateField>

此时,Discontinued列从CheckBox列转变为一对单选按钮(见图14)。当进入product编辑界面时,discontinued对应的单选按钮被选中,点击更新时也会将新的状态更新到数据库。


图14:表示Discontinued的CheckBox被替换成一对单选按钮

注意:由于Product数据库中的Discontinued字段不允许为NULL值,所以显示界面中不用考虑NULL的情况。不过如果Discontinued允许NULL时,就要在列表中增加第3个单选项,值设为空字符串(Value=””),就像category和supplier的下拉框那样。

小结

由于绑定列和CheckBox列自动呈现了只读、编辑和新增界面,缺少定制能力。可是我们却经常需要对新增和编辑界面进行定制,比如增加验证控件(上节教程)或定制数据集的用户界面(本节教程)。用模板列TemplateField定制界面总结为以下几步:

    1. 增加模板列或者将现有的绑定列、CheckBox列转为模板列。
    2. 按照实际需要给界面增加控件
    3. 给新增加的控件进行相关字段的数据绑定。

定制过程除了使用内建的ASP.NET控件,也可以在模板列中使用自定义控件,编译过的服务器控件以及用户控件。

祝编程快乐!


作者简介

Scott Mitchell,著有六本ASP/ASP.NET方面的书,是4GuysFromRolla.com的创始人,自1998年以来一直应用微软Web技术。Scott是个独立的技术咨询顾问,培训师,作家,最近完成了将由Sams出版社出版的新作, 《24小时内精通ASP.NET 2.0》(英文) 。 他的联系电邮为mitchell@4guysfromrolla.com,也可以通过他的博客http://ScottOnWriting.NET与他联系。

0
相关文章