This demo illustrates how to add functionality to the DataGrid to allow the user to delete a
file by clicking a "Delete" button next to the file's name. (Note that for this demo, clicking
the Delete button does not actually Delete the file... it simply emits a message explaining what
file you opted to delete...)
Source Code
<%@ Import Namespace="System.IO" %>
<script language="VB" runat="server">
Sub Page_Load(sender as Object, e as EventArgs)
If Not Page.IsPostBack then
Dim dirInfo as New DirectoryInfo(Server.MapPath(""))
articleList.DataSource = dirInfo.GetFiles("*.aspx")
articleList.DataBind()
End If
End Sub
Sub articleList_ItemDataBound(sender as Object, e as DataGridItemEventArgs)
' First, make sure we're NOT dealing with a Header or Footer row
If e.Item.ItemType <> ListItemType.Header AND _
e.Item.ItemType <> ListItemType.Footer then
'Now, reference the Button control that the Delete ButtonColumn
'has been rendered to
Dim deleteButton as Button = e.Item.Cells(0).Controls(0)
'We can now add the onclick event handler
deleteButton.Attributes("onclick") = "javascript:return " & _
"confirm('Are you sure you want to delete the file " & _
DataBinder.Eval(e.Item.DataItem, "Name") & "?')"
End If
End Sub
Sub articleList_DeleteFile(sender as Object, e as DataGridCommandEventArgs)
'First, get the filename to delete
Dim fileName as String = articleList.DataKeys(e.Item.ItemIndex)
lblMessage.Text = "You opted to delete the file " & fileName & ".<br />" & _
"This file could be deleted by calling: <code>File.Delete(fileName)</code><p>"
'You would want to rebind the Directory's files to the DataGrid after
'deleting the file...
End Sub
</script>
<form runat="server">
<asp:label runat="server" id="lblMessage" Font-Italic="True" ForeColor="Red" />
<asp:DataGrid runat="server" id="articleList" Font-Name="Verdana"
AutoGenerateColumns="False" AlternatingItemStyle-BackColor="#eeeeee"
HeaderStyle-BackColor="Navy" HeaderStyle-ForeColor="White"
HeaderStyle-Font-Size="15pt" HeaderStyle-Font-Bold="True"
DataKeyField="FullName"
OnItemDataBound="articleList_ItemDataBound"
OnDeleteCommand="articleList_DeleteFile">
<Columns>
<asp:ButtonColumn Text="Delete" ButtonType="PushButton" CommandName="Delete" />
<asp:HyperLinkColumn DataNavigateUrlField="Name" DataTextField="Name" HeaderText="File Name" />
<asp:BoundColumn DataField="LastWriteTime" HeaderText="Last Write Time"
ItemStyle-HorizontalAlign="Center" DataFormatString="{0:d}" />
<asp:BoundColumn DataField="Length" HeaderText="File Size"
ItemStyle-HorizontalAlign="Right" DataFormatString="{0:#,### bytes}" />
</Columns>
</asp:DataGrid>
</form>