理器实现的功能相似 。根据实现的功能,我划分为2个方法:
.ProcessBrochureUpload (FileUpload, out bool):它以一个FileUpload控件实例为输入参数,结果为一 个布尔值(Boolean)。根据该布尔值判断是否继续更新或删除操作,抑或取消操 作。如果存在上传文件该方法就返回其路径,反之返回null。
.DeleteRememberedBrochurePath:如果页面变量 deletedCategorysPdfPath不为null,则删除该参数指定的文件。
下面是 上述2种方法的代码。注意ProcessBrochureUpload方法和DetailsView控件的 ItemInserting事件处理器有某些相似性,在本章,我们更新DetailsView控件的 事件处理器以使用这些新方法。下载本章的代码,查看我们对DetailsView控件的 事件处理器所做的修改。
private string ProcessBrochureUpload
(FileUpload BrochureUpload, out bool CancelOperation)
{
CancelOperation = false; // by default, do not cancel operation
if (BrochureUpload.HasFile)
{
// Make sure that a PDF has been uploaded
if (string.Compare (System.IO.Path.GetExtension(BrochureUpload.FileName),
".pdf", true) != 0)
{
UploadWarning.Text =
"Only PDF documents may be used for a category''s brochure.";
UploadWarning.Visible = true;
CancelOperation = true;
return null;
}
const string BrochureDirectory = "~/Brochures/";
string brochurePath = BrochureDirectory + BrochureUpload.FileName;
string fileNameWithoutExtension =
System.IO.Path.GetFileNameWithoutExtension(BrochureUpload.FileName);
int iteration = 1;
while (System.IO.File.Exists(Server.MapPath(brochurePath)))
{
brochurePath = string.Concat(BrochureDirectory, fileNameWithoutExtension,
"-", iteration, ".pdf");
iteration++;
}
// Save the file to disk and set the value of the brochurePath parameter
BrochureUpload.SaveAs (Server.MapPath(brochurePath));
return brochurePath;
}
else
{
// No file uploaded
return null;
}
}
private void DeleteRememberedBrochurePath()
{
// Is there a file to delete?
if (deletedCategorysPdfPath != null)
{
System.IO.File.Delete(Server.MapPath (deletedCategorysPdfPath));
}
}
在GridView控 件的RowUpdating和RowUpdated事件处理器里使用上面2个方法,如下:
protected void Categories_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
// Reference the RadioButtonList
RadioButtonList BrochureOptions =
(RadioButtonList)Categories.Rows[e.RowIndex].FindControl ("BrochureOptions");
// Get BrochurePath information about the record being updated
int categoryID = Convert.ToInt32(e.Keys["CategoryID"]);
CategoriesBLL categoryAPI = new CategoriesBLL();
Northwind.CategoriesDataTable categories =
categoryAPI.GetCategoryByCategoryID(categoryID);
Northwind.CategoriesRow category = categories[0];
if (BrochureOptions.SelectedValue == "
|