Fileupload inside detailsview in edit mode
您好,我尝试在详细信息视图中添加文件上传,我在此处附上我的代码中的一些部分:
1 2 3 | <asp:DetailsView ID="DetailsView1" runat="server" Height="50px" Width="586px" DefaultMode="Edit" AutoGenerateRows="False" BorderColor="White" BorderStyle="None" DataSourceID="EntityDataSource1" GridLines="None" DataKeyNames="UserName" OnItemUpdated="DetailsView1_ItemUpdated" ONItemEditing="DetailsView1_ItemEditing"> |
然后文件上传控件被放置在模板字段内:
1 2 3 4 5 6 | <EditItemTemplate> </EditItemTemplate> </asp:TemplateField> |
,数据源是:
1 2 3 4 5 6 7 8 9 | <asp:EntityDataSource ID="EntityDataSource1" runat="server" ConnectionString="name=mesteriEntities" DefaultContainerName="mesteriEntities" EnableFlattening="False" EntitySetName="Users" EnableUpdate="True" AutoGenerateWhereClause="True" EnableInsert="True"> <WhereParameters> </WhereParameters> </asp:EntityDataSource> |
背后的代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | protected void DetailsView1_ItemEditing(object sender, DetailsViewInsertEventArgs e) { FileUpload fu1 = (FileUpload)DetailsView1.FindControl("FileUpload1"); if (fu1 == null) e.Cancel = true; if (fu1.HasFile) { try { string fileName = Guid.NewGuid().ToString(); string virtualFolder ="~/UserPics/"; string physicalFolder = Server.MapPath(virtualFolder); // StatusLabel.Text ="Upload status: File uploaded!"; string extension = System.IO.Path.GetExtension(fu1.FileName); fu1.SaveAs(System.IO.Path.Combine(physicalFolder, fileName + extension)); e.Values["foto"] = System.IO.Path.Combine(physicalFolder, fileName + extension); } catch (Exception ex) { Response.Write(ex.Message); } } else e.Cancel = true; } |
我不确定为什么不起作用。它不会将文件上传到服务器上,也不会在文件的数据库中添加引用。为什么我在这里做错了?
谢谢你
据我所知(通过查看类文档:DetailsView Class)没有要处理的 OnItemEditing 事件?
但是有一个 DetailsView.ItemUpdating 事件看起来可以解决问题:
Occurs when an Update button within a DetailsView control is clicked,
but before the update operation.
我还认为找不到 FileUpload 控件,因为 FindControl 方法没有搜索它包含的控件的完整层次结构。
尝试使用以下方法并像这样修改您的代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | FileUpload fu1 = (FileUpload)FindControl(DetailsView1,"FileUpload1"); ... private Control FindControl(Control parent, string id) { foreach (Control child in parent.Controls) { string childId = string.Empty; if (child.ID != null) { childId = child.ID; } if (childId.ToLower() == id.ToLower()) { return child; } else { if (child.HasControls()) { Control response = FindControl(child, id); if (response != null) return response; } } } return null; } |