To read the article online, visit http://www.4GuysFromRolla.com/articles/052803-1.2.aspx

Displaying the Files in a Directory using a DataGrid, Part 2

By Scott Mitchell


  • Read Part 1

  • In Part 1 we saw how to create a DataGrid that listed the contents of the files in a directory. In this part we'll augment this example to allow users to delete a file from the list by simply clicking a button.

    Adding a Delete Button to the DataGrid


    Imagine that we wanted to enhance our previous example as to allow the user to delete a file from the directory. To accomplish this we can add a ButtonColumn titled "Delete" to the DataGrid. The following DataGrid declaration shows the DataGrid after the "Delete" button has been added:

    <form runat="server">
      <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"
        <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>
      

    After examining the above code sample, be sure to note the following three things:

    1. A ButtonColumn has been added to the DataGrid, which displays a "Delete" button.
    2. The ButtonColumn's CommandName property has been set to Delete. This has the effect of having the DataGrid's DeleteCommand event fire when this button is clicked.
    3. The DataGrid has been placed inside a Web form (the <form runat="server">...</form>). This is requires since the DataGrid now contains a ButtonColumn.

    Now, we need to wire up an event handler for the DataGrid's DeleteCommand. This event handler will fire whenever one of the DataGrid's row's "Delete" buttons is clicked, so the code in the event handler must first determine the path of the file that we wish to delete, and then actually delete the file.

    In order to determine the file that the user wants to delete, let's set the DataGrid's DataKeyField to the FullName property of the FileInfo class. Doing so will mean that we can easily determine the full file path of the row whose "Delete" button was clicked. To accomplish this simply set the DataKeyField property to FullName, like so:

    <form runat="server">
      <asp:DataGrid runat="server" id="articleList" 
          ...
          DataKeyField="FullName">
        <Columns>
          ...
        </Columns>
      </asp:DataGrid>
    </form>
      

    All that remains is to create an event handler for the DataGrid's DeleteCommand event. In this event handler, we need to determine the file to delete and then delete it via the File.Delete() method. The final code example can be seen below, and contains a live demo. In addition to the code to delete the file, the sample code also contains a means for adding a client-side confirmation popup box so that when the user clicks a "Delete" button they are prompted as to whether or not they want to, indeed, delete the file. (A thorough discussion on adding such client-side events to a DataGrid's ButtonColumn can be found in: An Extensive Examination of the DataGrid Web Control: Part 8!)

    <%@ 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>
      
    [View a Live Demo!]

    Conclusion


    In this article we saw how to use the .NET Framework's file system-related classes, and how to use a DataGrid to display the files in a given directory. In addition, we looked at enhancing the DataGrid so that it included a column of "Delete" buttons, thereby allowing the user to delete a file displayed in the list of files. All of this was accomplished with a minimal amount of code and development time...

    Happy Programming!

  • By Scott Mitchell


    Further Reading:


  • Displaying Files and Folders in a GridView
  • Article Information
    Article Title: ASP.NET.Displaying the Files in a Directory using a DataGrid, Part 2
    Article Author: Scott Mitchell
    Published Date: May 28, 2003
    Article URL: http://www.4GuysFromRolla.com/articles/052803-1.2.aspx


    Copyright 2017 QuinStreet Inc. All Rights Reserved.
    Legal Notices, Licensing, Permissions, Privacy Policy.
    Advertise | Newsletters | E-mail Offers