File Download button in RadGrid

12 posts, 0 answers
  1. M
    M avatar
    24 posts
    Member since:
    Jul 2012

    Posted 23 Jul 2012 Link to this post

    I'm trying to create a download link in a RadGrid. What is missing?
    How can I get this to work?
    Unless someone has a different solution.
    Thank you for your help.
    Mike
    <telerik:RadGrid ID="RadGrid1" runat="server" DataSourceID="SqlDataSource1">
                <MasterTableView autogeneratecolumns="False" datakeynames="id" datasourceid="SqlDataSource1">
                <CommandItemSettings ExportToPdfText="Export to PDF"></CommandItemSettings>
     
                <RowIndicatorColumn FilterControlAltText="Filter RowIndicator column">
                <HeaderStyle Width="20px"></HeaderStyle>
                </RowIndicatorColumn>
     
                <ExpandCollapseColumn FilterControlAltText="Filter ExpandColumn column">
                <HeaderStyle Width="20px"></HeaderStyle>
                </ExpandCollapseColumn>
     
                    <Columns>
                        <telerik:GridButtonColumn CommandName="download_file" Text="Download" UniqueName="Download" HeaderText="Download"></telerik:GridButtonColumn>
                        <telerik:GridBoundColumn DataField="id" DataType="System.Int32" FilterControlAltText="Filter id column" HeaderText="id" ReadOnly="True" SortExpression="id" UniqueName="id">
                        </telerik:GridBoundColumn>
                        <telerik:GridBoundColumn DataField="file_name" FilterControlAltText="Filter file_name column" HeaderText="file_name" SortExpression="file_name" UniqueName="file_name">
                        </telerik:GridBoundColumn>
                        <telerik:GridBoundColumn DataField="file_url" FilterControlAltText="Filter file_url column" HeaderText="file_url" SortExpression="file_url" UniqueName="file_url">
                        </telerik:GridBoundColumn>
                    </Columns>
     
                <EditFormSettings>
                <EditColumn FilterControlAltText="Filter EditCommandColumn column"></EditColumn>
                </EditFormSettings>
                </MasterTableView>
     
                <FilterMenu EnableImageSprites="False"></FilterMenu>
     
                <HeaderContextMenu CssClass="GridContextMenu GridContextMenu_Default"></HeaderContextMenu>
            </telerik:RadGrid>
    protected void RadGrid1_ItemCommand(object source, Telerik.Web.UI.GridCommandEventArgs e)
        {
             
     
            if (e.CommandName == "download_file")
            {
                string filename=e.CommandArgument.ToString();
                string path=MapPath("~/files/" + filename);
                byte []bts=System.IO.File.ReadAllBytes(path);
                Response.Clear();
                Response.ClearHeaders();
                Response.AddHeader("Content-Type", "Application/octet-stream");
                Response.AddHeader("Content-Length",bts.Length.ToString());
                Response.AddHeader("Content-Disposition","attachment; filename=" + filename);
                Response.BinaryWrite(bts);
                Response.Flush();
                Response.End();
            }
        }

  2. Shinu
    Shinu avatar
    17764 posts
    Member since:
    Mar 2007

    Posted 24 Jul 2012 Link to this post

    Hi Mike,

    You will not be able to get the CommandArgument in the ItemCommand event without setting it.Since the sender is the GridButtonColumn, you need to set the CommandArgument in the ASPX. But here I suppose, you need the filename from the DataField 'file_name' which is bound to a BoundColumn.Please check the following code snippet to get the BoundColumn Value in the ItemCommand event.

    C#:
    protected void RadGrid1_ItemCommand(object sender, Telerik.Web.UI.GridCommandEventArgs e)
    {
        if (e.CommandName == "download_file")
        {
            GridDataItem ditem = (GridDataItem)e.Item;
            string filename = ditem["file_name"].Text; // get the filename from the row in which the download button is clicked   
            string path = MapPath("/sample/" + filename);
            byte[] bts = System.IO.File.ReadAllBytes(path);
            Response.Clear();
            Response.ClearHeaders();
            Response.AddHeader("Content-Type", "Application/octet-stream");
            Response.AddHeader("Content-Length", bts.Length.ToString());
            Response.AddHeader("Content-Disposition", "attachment; filename=" + filename);
            Response.BinaryWrite(bts);
            Response.Flush();
            Response.End();
        }
    }

    Thanks,
    Shinu.
  3. UI for ASP.NET Ajax is Ready for VS 2017
  4. M
    M avatar
    24 posts
    Member since:
    Jul 2012

    Posted 24 Jul 2012 Link to this post

    Shinu, Thanks for your help, but when I run the code, click on the Download button in the RadGrid, nothing happens.
    In debug mode it appears that the 'If (e.CommandName == "download_file") ' isn't being executed.
    In the 'browser ' view source here is the code line:
    <a href="javascript:__doPostBack('RadGrid1$ctl00$ctl04$ctl01','')">Download</a>


  5. Shinu
    Shinu avatar
    17764 posts
    Member since:
    Mar 2007

    Posted 25 Jul 2012 Link to this post

    Hi Mike,

    Are you attaching the ItemCommand event for RadGrid? Can you please check whether the ItemCommand event is firing or not. Make sure that you have attached the ItemCommand event in ASPX/C# as follows.

    ASPX:
    <telerik:RadGrid ID="RadGrid1" runat="server" DataSourceID="SqlDataSource1"
                onitemcommand="RadGrid1_ItemCommand">

    OR

    C#:
    protected void Page_Load(object sender, EventArgs e)  
    {
       RadGrid1.ItemCommand += new GridCommandEventHandler(RadGrid1_ItemCommand);
    }
    void RadGrid1_ItemCommand(object sender, GridCommandEventArgs e)
    {
       //your code
    }

    Thanks,
    Shinu.
  6. M
    M avatar
    24 posts
    Member since:
    Jul 2012

    Posted 25 Jul 2012 Link to this post

    Thank you that worked.
    It's always the simple things ;-)
  7. Jaime
    Jaime avatar
    8 posts
    Member since:
    Dec 2012

    Posted 11 Dec 2012 Link to this post

    Hi, I try his but i have a trouble when click on button to download the function the variable filename don`t get filename from the row "DocumentoConvocatoria". I've tried other fields and get the content correctly but not for column "DocumentosConvocatoria". Reviewing the recorded file name in this field has no spaces at the beginning or end. Any idea???

    protected void RadGrid1_ItemCommand(object sender, GridCommandEventArgs e)
    {
        if (e.CommandName == "download_file")
        {
     
            GridDataItem ditem = (GridDataItem)e.Item;
     
            string filename = ditem["DocumentoConvocatoria"].Text;    // get the filename from the row in which the download button is clicked   
     
            string path = MapPath("Admin/" + filename);
     
            byte[] bts = System.IO.File.ReadAllBytes(path);
     
            Response.Clear();
     
            Response.ClearHeaders();
     
            Response.AddHeader("Content-Type", "Application/octet-stream");
     
            Response.AddHeader("Content-Length", bts.Length.ToString());
     
            Response.AddHeader("Content-Disposition", "attachment; filename=" + filename);
     
            Response.BinaryWrite(bts);
     
            Response.Flush();
     
            Response.End();
     
        }
    }
  8. Shinu
    Shinu avatar
    17764 posts
    Member since:
    Mar 2007

    Posted 14 Dec 2012 Link to this post

    Hi,

    Please make sure that the column with UniqueName as 'DocumentoConvocatoria' looks and behaves like a Tablecell(GridBoundColumn) in the view mode.

    Please elaborate your scenario if it doesn't help.

    Regards,
    Shinu.
  9. Manish
    Manish avatar
    64 posts
    Member since:
    Jul 2011

    Posted 05 May 2014 in reply to Shinu Link to this post

    Hi Shinu,

    I have saved my files in file stream and i have used a template link button in my radgrid, Now i am trying to download but not able to download that file because i have used ajax manager in my grid and that ajax manager making problem in file save popup

    please check my problem as i am in big trouble

    On item command
      else if (e.CommandName == "DownloadFile")
                        {

                                SqlConnection objSqlCon = new SqlConnection(db.ConnectionString);
                                objSqlCon.Open();
                                SqlTransaction objSqlTran = objSqlCon.BeginTransaction();

                                SqlCommand objSqlCmd = new SqlCommand("up_Get_Document_File", objSqlCon, objSqlTran);
                                objSqlCmd.CommandType = CommandType.StoredProcedure;

                                SqlParameter objSqlParam1 = new SqlParameter("@FileGUID", SqlDbType.VarChar);
                                objSqlParam1.Value = e.CommandArgument;

                                objSqlCmd.Parameters.Add(objSqlParam1);
                                string path = string.Empty;
                                string FileType = string.Empty;
                                string FormName = string.Empty;

                                using (SqlDataReader sdr = objSqlCmd.ExecuteReader())
                                {
                                    while (sdr.Read())
                                    {
                                        path = sdr[0].ToString();
                                        FileType = sdr[1].ToString();
                                        FormName = sdr[2].ToString();
                                    }

                                }

                                objSqlCmd = new SqlCommand("SELECT GET_FILESTREAM_TRANSACTION_CONTEXT()", objSqlCon, objSqlTran);
                                byte[] objContext = (byte[])objSqlCmd.ExecuteScalar();
                                SqlFileStream objSqlFileStream = new SqlFileStream(path, objContext, FileAccess.Read);
                                byte[] buffer = new byte[(int)objSqlFileStream.Length];
                                objSqlFileStream.Read(buffer, 0, buffer.Length);
                                objSqlFileStream.Close();

                                objSqlTran.Commit();
                                FormName = FormName.Replace(";", "").Replace(",", " ");
                                Response.AddHeader("Content-disposition", "attachment; filename=" + Path.GetFileName(FormName) + FileType);
                                // Here you need to manage the download file stuff according to your need
                                Response.ContentType = "application/octet-stream";
                                Response.BinaryWrite(buffer);
                                Response.End();
                            
                        }

    and ajax have ajax manager on my aspx page 
     
  10. Radoslav
    Admin
    Radoslav avatar
    1564 posts

    Posted 08 May 2014 Link to this post

    Hello Manish,

    To achieve the desired functionality you can try disabling the ajax when the download link button is pressed. For example:
    <telerik:RadAjaxManager ID="RadAjaxManager1" ClientEvents-OnRequestStart="onRequestStart"
            runat="server">
     
    function onRequestStart(sender, args) {
      if (args.get_eventTarget().indexOf("DownloadLinkButtonID") >= 0)
        args.set_enableAjax(false);
    }

    Please give it try and let me know if it helps you.

    Regards,
    Radoslav
    Telerik
     

    Check out the Telerik Platform - the only platform that combines a rich set of UI tools with powerful cloud services to develop web, hybrid and native mobile apps.

     
  11. Payal
    Payal avatar
    5 posts
    Member since:
    Jun 2014

    Posted 18 Jun 2014 Link to this post

    This is not working for me. Is the download code required to be changed according to the type of file we are trying to downlaod
  12. Radoslav
    Admin
    Radoslav avatar
    1564 posts

    Posted 20 Jun 2014 Link to this post

    Hi Payal,

    Could you please elaborate a bit more or your scenario? Why the provided code snippet does not work in your case? Do any error occurs or unexpected results? Also could you please post your aspx markup code with the related code behind file. Thus we will be able to gather more details about your scenario and provide you with more to-the-point answer.

    Looking forward for your reply.

    Regards,
    Radoslav
    Telerik
     

    Check out the Telerik Platform - the only platform that combines a rich set of UI tools with powerful cloud services to develop web, hybrid and native mobile apps.

     
  13. Payal
    Payal avatar
    5 posts
    Member since:
    Jun 2014

    Posted 20 Jun 2014 Link to this post

    Thanks for your response.

    I could resolve the issue.
Back to Top
UI for ASP.NET Ajax is Ready for VS 2017