为定制ImageField的编辑界面,我们需要将其转化为一个TemplateField。在GridView控件的智能标签里点击“编辑列”,进入后选中ImageField,再点击“Convert this field into a TemplateField”链接。
图16:将ImageField转换为TemplateField
转换后的TemplateField由2个模版构成。就像下面的声明代码显示的那样,ItemTemplate模版包含一个Image Web控件,其ImageUrl属性由一个数据绑定语法指定,该数据绑定语法基于ImageField的DataImageUrlField和 DataImageUrlFormatString属性。而EditItemTemplate模版则包含一个TextBox,其Text属性绑定到DataImageUrlField属性的值。
<asp:TemplateField> <EditItemTemplate> <asp:TextBox runat="server" Text='<%# Eval("CategoryID") %>'></asp:TextBox> </EditItemTemplate> <ItemTemplate> <asp:Image runat="server" ImageUrl='<%# Eval("CategoryID", "DisplayCategoryPicture.aspx?CategoryID={0}") %>' /> </ItemTemplate> </asp:TemplateField>
我们需要更新EditItemTemplate模版以包含一个FileUpload控件。从GridView控件的智能标签点“编辑模版”,再在下拉列表选择Picture TemplateField的EditItemTemplate模版。在模版里你会看见一个TextBox,将其删除。从工具箱里拖一个FileUpload控件到页面,设其ID为PictureUpload。同时在模版里添加如下的文本:“To change the category's picture, specify a new picture. To keep the category's picture the same, leave the field empty”。
图17:在EditItemTemplate模版里添加一个FileUpload控件
完成定制该编辑界面后,在浏览器里查看。在只读模式里,类的图片和以前没什么两样,当点击Edit按钮时,picture列将呈现一段文本和一个FileUpload控件。
图18:编辑界面包含一个FileUpload控件
记得我们设置ObjectDataSource控件调用CategoriesBLL的UpdateCategory方法,该方法的一个输入参数为数组,用于处理图片的数据。如果该数组为null值,则调用另一个重载的UpdateCategory方法,该重载的UpdateCategory方法的UPDATE SQL语句不会更改Picture列,因此类的图片不会由任何变化。在GridView控件的RowUpdating事件处理器里,我们编程访问名为PictureUpload的FileUpload控件,判断是否上传了文件。如果没有文件上传,我们将不会为参数picture指定值;反之,如果上传了文件,我们将确保其为JPG格式的文件,并通过参数picture将其传给ObjectDataSource控件。
就像第6步里的代码一样,我们此时将要用到的绝大多数的代码已经存在于DetailsView控件的ItemInserting事件处理器里了。现在我们创建一个新的方法ValidPictureUpload,并更新ItemInserting事件处理器以使用该方法。
在GridView控件的RowUpdating事件处理器的开头部分添加如下的代码,这很重要,因为我们不希望将一个不符合条件的上传文件存储在文件系统。
// Reference the PictureUpload FileUpload FileUpload PictureUpload = (FileUpload)Categories.Rows[e.RowIndex].FindControl("PictureUpload"); if (PictureUpload.HasFile) { // Make sure the picture upload is valid if (ValidPictureUpload(PictureUpload)) { e.NewValues["picture"] = PictureUpload.FileBytes; } else { // Invalid file upload, cancel update and exit event handler e.Cancel = true; return; } }
ValidPictureUpload(FileUpload)方法只有一个FileUpload控件类型的输入参数,通过检查上传文件的扩展符以确保上传的文件为JPG格式。只有当上传了文件时才会调用该方法;如果没有文件上传,参数picture就只能使用其默认值—null。如果上传了图片,且ValidPictureUpload方法返回值true,将用图片的二进制数据对参数picture赋值。如果ValidPictureUpload方法返回值false,则取消更新,并退出事件处理器。
ValidPictureUpload(FileUpload)方法的代码如下:
private bool ValidPictureUpload(FileUpload PictureUpload) { // Make sure that a JPG has been uploaded if (string.Compare(System.IO.Path.GetExtension(PictureUpload.FileName), ".jpg", true) != 0 && string.Compare(System.IO.Path.GetExtension(PictureUpload.FileName), ".jpeg", true) != 0) { UploadWarning.Text = "Only JPG documents may be used for a category's picture."; UploadWarning.Visible = true; return false; } else { return true; } }
第8步:将原始几个类的图片替换为JPG格式