Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Open File From DataGrid HyperLink

Status
Not open for further replies.

TallOne

Programmer
May 14, 2004
164
US
Hello,

I have a datagrid that I build the datasource like this:
Code:
'Code Behind
Dim dirInfo As New DirectoryInfo(Global.g_sCONNAttachRoot)
        dgConnFiles.DataSource = dirInfo.GetFiles(sCoAbbrev & "-*.*")
        dgConnFiles.DataBind()

And here is the HTML...

Code:
<asp:datagrid id="dgConnFiles" style="BACKGROUND-COLOR: aliceblue" runat="server" Width="100%" Font-Size="xx-Small"
Font-Names="verdana,arial,helvetica,sans-serif" bordercolor="white" cellpadding="1" Cellspacing="0" AutoGenerateColumns="False" BorderWidth="1" HeaderStyle-Font-Bold="True" HeaderStyle-ForeColor="Navy" HeaderStyle-BackColor="lightsteelblue" DataKeyField="FullName">

<AlternatingItemStyle Wrap="False"></AlternatingItemStyle>
<ItemStyle Wrap="False" HorizontalAlign="Center"></ItemStyle>
<Columns>
<asp:ButtonColumn  HeaderText="Delete" Text="Delete" ButtonType="LinkButton" CommandName="Delete"  ItemStyle-HorizontalAlign="Left" />

<asp:HyperLinkColumn DataNavigateUrlField="Name" DataTextField="Name" HeaderText="File Name" ItemStyle-HorizontalAlign="Left" />
</Columns>
</asp:DataGrid>

I need to be able for the file to open once the hyperlink is clicked. Anyone know how to do this???
 
You will have to redirect to a page and set the content type to the type of file you are trying to open. And remember, you code will only get files on the server, not on a client machine.
 
I'd like to use something like below and the user gets presented with a dialog open/save/cancel But I'm stuck on the code... :(

Code:
        Response.Clear()
        Response.ContentType = mimetype
        Response.AddHeader("Content-Disposition", "attachment; filename=" & filename & "")
        Response.Flush()
        Response.WriteFile(filepath)
        Response.End()
 
How big are the files? That code won't work for large files, you need to do it in a different way.

I recently worked on a project where you download files from a GridView but it would be similar for a DataGrid. The HyperLinkField in the grid looked like this:
Code:
<asp:HyperLinkField DataNavigateUrlFields="FileName" HeaderText="Results"
	DataNavigateUrlFormatString="GenerateFile.aspx?FileName={0}" DataTextField="LinkText">
</asp:HyperLinkField>
The GenerateFile.aspx page is blank with this code behind it (mostly ripped from a Microsoft article):
Code:
using System;
using System.Configuration;

public partial class GenerateFile : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        System.IO.Stream iStream = null;

        string sFullFileName;
        string sFileName = Request.QueryString["FileName"];
        string sOutputPath = ConfigurationManager.AppSettings["DownloadFilesPath"];

        sFullFileName = sOutputPath + "\\" + sFileName;

        // Buffer to read 10K bytes in chunk:
        byte[] buffer = new Byte[10000];

        // Length of the file:
        int length;

        // Total bytes to read:
        long dataToRead;

        // Check whether file exists
        if (System.IO.File.Exists(sFullFileName))
        {
            try
            {
                // Open the file.
                iStream = new System.IO.FileStream(sFullFileName, System.IO.FileMode.Open,
                            System.IO.FileAccess.Read, System.IO.FileShare.Read);

                // Total bytes to read:
                dataToRead = iStream.Length;

                Response.ContentType = "application/octet-stream";
                Response.AddHeader("Content-Disposition", "attachment; filename=" + sFileName);

                // Read the bytes.
                while (dataToRead > 0)
                {
                    // Verify that the client is connected.
                    if (Response.IsClientConnected)
                    {
                        // Read the data in buffer.
                        length = iStream.Read(buffer, 0, 10000);

                        // Write the data to the current output stream.
                        Response.OutputStream.Write(buffer, 0, length);

                        // Flush the data to the HTML output.
                        Response.Flush();

                        buffer = new Byte[10000];
                        dataToRead = dataToRead - length;
                    }
                    else
                    {
                        //prevent infinite loop if user disconnects
                        dataToRead = -1;
                    }
                }
            }
            catch (Exception ex)
            {
            }
            finally
            {
                if (iStream != null)
                {
                    //Close the file.
                    iStream.Close();
                }
                Response.Close();
            }
        }
        else
        {
            Response.Write(String.Concat("Could not find the file: ", sFullFileName));
        }
    }
}
Hope that helps.

Nelviticus
 
Sorry just saw your reply...I got it to work fine...but I'm not at the puter with the code.. The files are RDP connections and not big at all. I like the isclientconnected method :)
 
I have another issue. One of the bound columns provides the size of the file in bytes. Does anyone know how to convert this to megabytes to display in the grid??

Code:
<asp:BoundColumn DataField="Length" HeaderText="File Size" ItemStyle-HorizontalAlign="Left"  HeaderStyle-Width="100px" DataFormatString="{0:#,### bytes}"/>

TIA!
 
I've been trying to use this function but i'm not having much luck on where to put the function call????


Code:
    Public Function xBytesToMegabytes(ByVal Bytes As Double) As Double
        Dim dblAns As Double
        dblAns = (Bytes / 1024) / 1024
        xBytesToMegabytes = Format(dblAns, "###,###,##0.00")
    End Function
 
I would recommend using a generic handler (ashx) instead of a webform (aspx) if all your doing is opening a file.

Jason Meckley
Programmer
Specialty Bakers, Inc.
 
Hi Jason,

I don't understand how that would resolve the issue of formatting the bound column(Length) which is bound to the collection returned by the getfiles method of directoryinfo...
 
it wouldn't it would simply be a better object to handle non-form related web requests.

Jason Meckley
Programmer
Specialty Bakers, Inc.
 
Here's what I ended up doing....
Code:
Sub DataGrid1_ItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DataGridItemEventArgs) Handles dgReports.ItemDataBound
If e.Item.ItemType <> ListItemType.Header And _
             e.Item.ItemType <> ListItemType.Footer Then
Dim sText As String = CStr(FormatNumber((CDbl(Trim(Replace(e.Item.Cells(3).Text, "bytes", ""))) / 1024 / 1024), 2))
e.Item.Cells(3).Text = sText & " MB"
End If
End Sub
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top