Solved

File download using datagrid and sort

Posted on 2004-08-15
4
345 Views
Last Modified: 2008-02-01
I am using the following code from www.4guysfromrolla.com that creates a sortable datagrid of files in a given folder.  I am storing a path in a database and want to be able to retrieve files based on that path.  This code uses the path of the control so I would have to have the control in the same directory as the control.  I can populate a variable easily enough with the string path in the database to load the files I want into the array, but how do i get that into the link on the datagrid?  All help is greatly appreciated.

ListArticles.Sortable.aspx

<%@ Page Language="vb" AutoEventWireup="false"
    Codebehind="ListArticles.Sortable.aspx.vb"
    Inherits="SortableFileEntries.ListArticleSortable"%>
<form runat="server" ID="Form1">
   <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"
       AllowSorting="True" OnSortCommand="sortDisplay">
    <Columns>
     <asp:HyperLinkColumn DataNavigateUrlField="Name" DataTextField="Name"
              HeaderText="File Name" SortExpression="FileName" />
     <asp:BoundColumn DataField="LastWriteTime" HeaderText="Last Write Time"
              ItemStyle-HorizontalAlign="Center" DataFormatString="{0:d}"
              SortExpression="LastWriteTime" />
     <asp:BoundColumn DataField="Length" HeaderText="File Size"
              ItemStyle-HorizontalAlign="Right"
              DataFormatString="{0:#,### bytes}"
              SortExpression="Length" />
    </Columns>
   </asp:DataGrid>
</form>    
            
Code-Behind Class - ListArticles.Sortable.aspx


Imports System.Collections
Imports System.IO

Public Class ListArticleSortable
  Inherits System.Web.UI.Page
  Protected WithEvents articleList As System.Web.UI.WebControls.DataGrid

#Region " Web Form Designer Generated Code "

  'This call is required by the Web Form Designer.
  <System.Diagnostics.DebuggerStepThrough()> _
  Private Sub InitializeComponent()

  End Sub

  Private Sub Page_Init(ByVal sender As System.Object, _
             ByVal e As System.EventArgs) _
             Handles MyBase.Init
    'CODEGEN: This method call is required by the Web Form Designer
    'Do not modify it using the code editor.
    InitializeComponent()
  End Sub

#End Region

  Private Sub Page_Load(ByVal sender As System.Object, _
          ByVal e As System.EventArgs) Handles MyBase.Load
    If Not Page.IsPostBack Then
      BindData(CompareByOptions.FileName)
    End If
  End Sub

  Private Sub BindData(ByVal compareMethod As CompareByOptions)
    Dim dirInfo As New DirectoryInfo(Server.MapPath(""))
    Dim fileInfoArray() As FileInfo = dirInfo.GetFiles()

    Array.Sort(fileInfoArray, New CompareFileInfoEntries(compareMethod))
    articleList.DataSource = fileInfoArray
    articleList.DataBind()
  End Sub

  Public Sub SortDisplay(ByVal sender As Object, ByVal e As _
                    DataGridSortCommandEventArgs)
    Select Case e.SortExpression
      Case "FileName"
        BindData(CompareByOptions.FileName)
      Case "LastWriteTime"
        BindData(CompareByOptions.LastWriteTime)
      Case "Length"
        BindData(CompareByOptions.Length)
    End Select
  End Sub
End Class


Public Enum CompareByOptions
  FileName
  LastWriteTime
  Length
End Enum


Public Class CompareFileInfoEntries
  Implements IComparer

  Private compareBy As CompareByOptions = CompareByOptions.FileName


  Public Sub New(ByVal cBy As CompareByOptions)
    compareBy = cBy
  End Sub

  Public Overridable Overloads Function Compare(ByVal file1 As _
         Object, ByVal file2 As Object) _
         As Integer Implements IComparer.Compare
    'Convert file1 and file2 to FileInfo entries
    Dim f1 As FileInfo = CType(file1, FileInfo)
    Dim f2 As FileInfo = CType(file2, FileInfo)

    'Compare the file names
    Select Case compareBy
      Case CompareByOptions.FileName
        Return String.Compare(f1.Name, f2.Name)
      Case CompareByOptions.LastWriteTime
        Return DateTime.Compare(f1.LastWriteTime, f2.LastWriteTime)
      Case CompareByOptions.Length
        Return f1.Length - f2.Length
    End Select
  End Function
End Class
0
Comment
Question by:stillgar
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 3
4 Comments
 

Author Comment

by:stillgar
ID: 11804202
The 3rd sentence should read:
This code uses the path of the control so I would have to have the control in the same directory as the files.
0
 
LVL 20

Accepted Solution

by:
ihenry earned 500 total points
ID: 11804545
If the paths are loaded from db, why not using dataview to make easier to do sorting. I made small modification to the code and load the data from xml file.

--------- aspx ----------------------------------------------------------------------
<%@ Page Language="vb" AutoEventWireup="false" Codebehind="WebForm4.aspx.vb" Inherits="webVB.WebForm4"%>
<HTML>
      <HEAD>
      </HEAD>
      <body>
            <form id="Form1" method="post" 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" AllowSorting="True" OnSortCommand="sortDisplay">
                        <Columns>
                              <asp:BoundColumn DataField="pub_id" HeaderText="Publisher ID" ItemStyle-HorizontalAlign="Center" SortExpression="pub_id" />
                              <asp:BoundColumn DataField="city" HeaderText="City" HeaderStyle-HorizontalAlign="Center" ItemStyle-HorizontalAlign="Center" SortExpression="city" />
                              <asp:HyperLinkColumn DataNavigateUrlField="Catalog" DataTextField="pub_name" HeaderText="File Name" SortExpression="pub_name" />
                        </Columns>
                  </asp:DataGrid>
            </form>
      </body>
</HTML>

--------- aspx.vb ----------------------------------------------------------------------
Public Class WebForm4
    Inherits System.Web.UI.Page

#Region " Web Form Designer Generated Code "

    'This call is required by the Web Form Designer.
    <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()

    End Sub
    Protected WithEvents articleList As System.Web.UI.WebControls.DataGrid

    'NOTE: The following placeholder declaration is required by the Web Form Designer.
    'Do not delete or move it.
    Private designerPlaceholderDeclaration As System.Object

    Private Sub Page_Init(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Init
        'CODEGEN: This method call is required by the Web Form Designer
        'Do not modify it using the code editor.
        InitializeComponent()
    End Sub

#End Region

    Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        'Put user code to initialize the page here
        If Not Page.IsPostBack Then
            BindData("pub_id")
        End If
    End Sub

    Public Sub SortDisplay(ByVal sender As Object, ByVal e As _
                      DataGridSortCommandEventArgs)
        BindData(e.SortExpression)
    End Sub

    Private Sub BindData(ByVal sortExpression As String)
        Dim ds As New DataSet
        ds.ReadXml(Server.MapPath("~/testdata.xml"))
        Dim dv As New DataView(ds.Tables(0))
        dv.Sort = sortExpression

        articleList.DataSource = dv
        articleList.DataBind()
    End Sub
End Class

--------- testdata.xml ----------------------------------------------------------------------
<?xml version="1.0" standalone="yes" ?>
<NewDataSet>
      <Table>
            <pub_id>0736</pub_id>
            <pub_name>New Moon Books</pub_name>
            <city>Boston</city>
            <state>MA</state>
            <country>USA</country>
            <catalog>c:\temp\catalogs\New_Moon_Books.pdf</catalog>
      </Table>
      <Table>
            <pub_id>0877</pub_id>
            <pub_name>Binnet &amp; Hardley</pub_name>
            <city>Washington</city>
            <state>DC</state>
            <country>USA</country>
            <catalog>c:\temp\catalogs\Binnet_Hardley.pdf</catalog>
      </Table>
      <Table>
            <pub_id>1389</pub_id>
            <pub_name>Algodata Infosystems</pub_name>
            <city>Berkeley</city>
            <state>CA</state>
            <country>USA</country>
            <catalog>c:\temp\catalogs\Algodata_Infosystems.pdf</catalog>
      </Table>
      <Table>
            <pub_id>1622</pub_id>
            <pub_name>Five Lakes Publishing</pub_name>
            <city>Chicago</city>
            <state>IL</state>
            <country>USA</country>
            <catalog>c:\temp\catalogs\Five_Lakes_Publishing.pdf</catalog>
      </Table>
      <Table>
            <pub_id>1756</pub_id>
            <pub_name>Ramona Publishers</pub_name>
            <city>Dallas</city>
            <state>TX</state>
            <country>USA</country>
            <catalog>c:\temp\catalogs\Ramona_Publishers.pdf</catalog>
      </Table>
      <Table>
            <pub_id>9901</pub_id>
            <pub_name>GGG&amp;G</pub_name>
            <city>München</city>
            <country>Germany</country>
            <catalog>c:\temp\catalogs\GGG_G.pdf</catalog>
      </Table>
      <Table>
            <pub_id>9952</pub_id>
            <pub_name>Scootney Books</pub_name>
            <city>New York</city>
            <state>NY</state>
            <country>USA</country>
            <catalog>c:\temp\catalogs\Scootney_Books.pdf</catalog>
      </Table>
      <Table>
            <pub_id>9999</pub_id>
            <pub_name>Lucerne Publishing</pub_name>
            <city>Paris</city>
            <country>France</country>
            <catalog>c:\temp\catalogs\Lucerne_Publishing.pdf</catalog>
      </Table>
</NewDataSet>


More information on displaying url/path
How to use HyperLink Column of DataGrid
http://www.c-sharpcorner.com/Code/2003/June/DataGridHyperLinkColumn.asp

and information on sorting datagrid
1. ASP.NET DataGrid Column Sorting
    http://www.dotnetjunkies.com/Tutorial/E169C6D4-D335-4D2B-AE3F-918EE3161815.dcik
2. Bidirectional Sorting Without ViewState Enabled
    http://aspalliance.com/articleViewer.aspx?aId=4&pId=

HTH
0
 

Author Comment

by:stillgar
ID: 11805131
My problem is that I am only storing the paths to folders & I do not know what the names of the files in the folders will be (they are changed by an outside process).   Would it be possible to do something like add a column to the array and populate it with the path from a variable  concatenated that with the "Name" property returned by DirectoryInfo.GetFiles?

Would it be possible to use a template column to somehow add the path at that point from a variable and display a link?

or could I use a bound column and hard code the html to make the text field a hyperlink and then pass in a variable containing the path?
0
 

Author Comment

by:stillgar
ID: 11806105
I found the answer in one of the pages that you posted (http://www.c-sharpcorner.com/Code/2003/June/DataGridHyperLinkColumn.asp).  The solution was really pretty simple in the end.  I just needed to create a function that would reformat the "Name" property so that it contained the rest of the URL.  I changed the hyperlinkcolumn to be a template column containing a hyperlinkcolumn with a function call to reformat the hyperlink.  The function is simply one located in the codebehind and the actual path and the URL are stored in a database.  The code is as follows.

            <asp:TemplateColumn HeaderText="File Name">
                        <ItemTemplate>
                              <asp:HyperLink runat="server" Text=' <%# DataBinder.Eval(Container, "DataItem.Name") %> ' NavigateUrl='<%#GetURL(DataBinder.Eval(Container, "DataItem.name")) %>'>
                              </asp:HyperLink>
                        </ItemTemplate>
                  </asp:TemplateColumn>



        Public Function GetURL(ByVal strFile As String) As String
            Dim TempString As String

            TempString = strPathQualifier & strFile

            strFile = Nothing

            Return TempString


0

Featured Post

Revamp Your Training Process

Drastically shorten your training time with WalkMe's advanced online training solution that Guides your trainees to action.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Sometimes in DotNetNuke module development you want to swap controls within the same module definition.  In doing this DNN (somewhat annoyingly) swaps the Skin and Container definitions to the default admin selections.  To get around this you need t…
In .NET 2.0, Microsoft introduced the Web Site.  This was the default way to create a web Project in Visual Studio 2005.  In Visual Studio 2008, the Web Application has been restored as the default web Project in Visual Studio/.NET 3.x The Web Si…
A short tutorial showing how to set up an email signature in Outlook on the Web (previously known as OWA). For free email signatures designs, visit https://www.mail-signatures.com/articles/signature-templates/?sts=6651 If you want to manage em…

751 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question