我试图从 Gridview1 中删除一条记录,同时单击一下从服务器上删除相应的图像文件。(Gridview1 中的每一行在服务器上都有一个关联的图像文件。)
要删除记录,我使用 asp:CommandField showDeleteButton="true"
了sqlDataSource
'DELETE
语句。
在这个过程中,我还使用了GridView1
“ onRowDeleting
”事件从服务器上删除了相应的图像文件。
这就是它的作用,我的代码如下:
- 记录确实被删除了,
- 服务器上的文件没有,
- 没有抛出任何错误(因为我猜它没有找到文件,这是预期的行为)。
另请考虑:在开始在 Gridview 上进行开发之前,我已经设置并测试了一个更简单的“查看文件是否可以从服务器上删除”测试。由于我们的文件位于托管公司服务器上,因此我想测试任何权限问题。其中: 在文本框中输入文件名和扩展名(“myImage.jpg”) 单击使用File.Delete
WhaaLa 方法的按钮 - 文件从服务器中消失。
但是,我无法让文件随着我的新设置而消失。这是代码:
<asp:GridView ID="GridView1" runat="server" AllowSorting="True" AutoGenerateColumns="False" DataKeyNames="libraryID"
DataSourceID="SqlDataSource1" Width="800px" onrowdeleting="deleteImageFromServer" CssClass="gridViewSmallText"
OnDataBound="rowCount">
<Columns>
<asp:CommandField ShowDeleteButton="True" />
<%--A link that goes to the uploadPage to upload a new version of the image--%>
<asp:HyperLinkField runat="server" HeaderText="SKU (Click to Update)" DataTextField="sku" DataNavigateUrlFields="sku" SortExpression="sku" DataNavigateUrlFormatString="graphicUpload.aspx?sku={0}" >
</asp:HyperLinkField>
<asp:TemplateField HeaderText="Image" SortExpression="imagePath">
<ItemTemplate>
<%--Pull the imagePath column from the database here-it also includes the image file --%>
<asp:Image ID="merchImage" runat="server" Height="100px" ImageUrl='<%# "http://www.ourcompanysite.net/" + DataBinder.Eval(Container.DataItem, "imagePath") %>' /><br />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="View Full Size">
<ItemTemplate>
<%--A link to view the image in it's full size in a new browser window--%>
<asp:HyperLink ID="fullSizeHyperlink" runat="server" NavigateUrl='<%# "http://www.leadingjewelersguild.net/" + DataBinder.Eval(Container.DataItem, "imagePath") %>' Text="View" Target="_blank" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="DateUpdated" </asp:BoundField>
<%---some date stuff here--%>
<asp:BoundField DataField="DateCreated" HeaderText="First Uploaded" SortExpression="DateCreated" >
</asp:BoundField>
</Columns>
</asp:GridView>
后面的代码:
protected void deleteImageFromServer(object sender, GridViewDeleteEventArgs e)
{
// I read from GridViewGuy.com that you're supposed to reference the row item via e.Values
string imageToDelete = e.Values["sku"] + ".jpg";
//I pulled the value of "imageToDelete" into a lable just to see what I was getting
//during the "onRowDeleting" and it reported back .jpg instead of the full file name
//myImage.jpg, so I guess this is the crux of my problem.
string image = Server.MapPath("/images/graphicsLib/" + imageToDelete);
string image = Server.MapPath("e:\\sites\\oursite\\files\\images\\graphicsLib\\" + imageToDelete);
if (File.Exists(image))
{
File.Delete(image);
}
//at this point the record from GridView1 is gone, but the file on server remains.
}