我正在尝试从GridView1中删除一条记录,同时单击一下即可从服务器上删除相应的图像文件。(GridView1中的每一行在服务器上都有一个关联的图像文件。)
要删除记录,我正在使用
asp:CommandField showDeleteButton="true"
伴随着
sqlDataSource
的
DELETE
语句。
在这个过程中,我也在使用
GridView1
“S”
onRowDeleting
“从服务器上删除相应图像文件的事件。
这是它的作用,我有下面的代码:
-
记录确实被删除了,
-
服务器上的文件没有,
-
没有抛出错误(因为我猜它找不到文件,这是预期的行为)。
还考虑:
我已经设置和测试了一个更简单的
“查看文件是否可以从
服务器“
在我开始开发GridView之前进行测试。因为我们的文件在主机上
公司服务器,我想测试任何权限问题。
由此:
将文件名和扩展名输入文本框(“myimage.jpg”)。
单击使用
File.Delete
方法
whala-文件从服务器上消失。
但是,我无法让文件离开我的新设置。
代码如下:
<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.
}