This is a migrated thread and some comments may be shown as answers.

File Download button in RadGrid

15 Answers 1267 Views
Grid
This is a migrated thread and some comments may be shown as answers.
M
Top achievements
Rank 1
M asked on 23 Jul 2012, 02:59 PM
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();
        }
    }

15 Answers, 1 is accepted

Sort by
0
Shinu
Top achievements
Rank 2
answered on 24 Jul 2012, 05:43 AM
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.
0
M
Top achievements
Rank 1
answered on 24 Jul 2012, 03:13 PM
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>


0
Shinu
Top achievements
Rank 2
answered on 25 Jul 2012, 06:51 AM
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.
0
M
Top achievements
Rank 1
answered on 25 Jul 2012, 01:10 PM
Thank you that worked.
It's always the simple things ;-)
0
Jaime
Top achievements
Rank 1
answered on 11 Dec 2012, 05:34 PM
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();
 
    }
}
0
Shinu
Top achievements
Rank 2
answered on 14 Dec 2012, 12:41 PM
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.
0
Manish
Top achievements
Rank 2
answered on 05 May 2014, 11:33 AM
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 
 
0
Radoslav
Telerik team
answered on 08 May 2014, 07:17 AM
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.

 
0
Payal
Top achievements
Rank 1
answered on 18 Jun 2014, 05:39 AM
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
0
Radoslav
Telerik team
answered on 20 Jun 2014, 11:22 AM
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.

 
0
Payal
Top achievements
Rank 1
answered on 20 Jun 2014, 12:10 PM
Thanks for your response.

I could resolve the issue.
0
Isaac
Top achievements
Rank 1
answered on 17 Mar 2017, 02:22 PM

Radoslav,

 

Thank you very much, the information you posted here solved my problem.

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);
}

Thanks.

0
Pronobesh
Top achievements
Rank 1
answered on 17 Apr 2017, 07:54 AM

Hello Shrinu,

I have written following code, which is not downloading file from Rad Grid control

 

 

<telerik:GridTemplateColumn HeaderText="Request Download" ItemStyle-HorizontalAlign="Center">
                                                <ItemTemplate>
                                                    <asp:ImageButton ID="imgDownload" runat="server" ImageUrl="~/Apps/QMx-CSER/Images/download1.png"
                                                        CommandName="DownloadFile" Height="22px" Width="22px" ToolTip="Request Download"
                                                        CommandArgument='<%# Eval("Job_ID") %>' />
                                                </ItemTemplate>
                                            </telerik:GridTemplateColumn>

 

 

else if (e.CommandName == "DownloadFile")
                {
                    int Job_ID = Convert.ToInt32(e.CommandArgument);
                    string AssemblyNumber = (e.Item.FindControl("lnkItemnumber") as LinkButton).Text;

                    string fullFileName = new SMTPMail().CreateExcel(Job_ID, AssemblyNumber, Session["User"].ToString());
                    string name = Path.GetFileNameWithoutExtension(fullFileName);
                    string extension = Path.GetExtension(fullFileName);
                    string fileName = name + "." + extension;

                    byte[] bts = System.IO.File.ReadAllBytes(fullFileName);
                    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();
                    File.Delete(fullFileName);
                    Response.End();                   
                }

 

Looking for your help on this.

 

Regards,

Pronobesh Mukherjee

0
Pronobesh
Top achievements
Rank 1
answered on 17 Apr 2017, 07:56 AM
Hello All,
I have written following code, which is not downloading file from Rad Grid control


<telerik:GridTemplateColumn HeaderText="Request Download" ItemStyle-HorizontalAlign="Center">
                                                <ItemTemplate>
                                                    <asp:ImageButton ID="imgDownload" runat="server" ImageUrl="~/Apps/QMx-CSER/Images/download1.png"
                                                        CommandName="DownloadFile" Height="22px" Width="22px" ToolTip="Request Download"
                                                        CommandArgument='<%# Eval("Job_ID") %>' />
                                                </ItemTemplate>
                                            </telerik:GridTemplateColumn>


else if (e.CommandName == "DownloadFile")
                {
                    int Job_ID = Convert.ToInt32(e.CommandArgument);
                    string AssemblyNumber = (e.Item.FindControl("lnkItemnumber") as LinkButton).Text;

                    string fullFileName = new SMTPMail().CreateExcel(Job_ID, AssemblyNumber, Session["User"].ToString());
                    string name = Path.GetFileNameWithoutExtension(fullFileName);
                    string extension = Path.GetExtension(fullFileName);
                    string fileName = name + "." + extension;

                    byte[] bts = System.IO.File.ReadAllBytes(fullFileName);
                    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();
                    File.Delete(fullFileName);
                    Response.End();                   
                }

Looking for your help on this.

Regards,
Pronobesh Mukherjee
0
Marin Bratanov
Telerik team
answered on 17 Apr 2017, 08:12 AM

Hi Pronobesh,

Make sure the button does not invoke a partial postback. You can only send files to the browser during a full postback. The approach shown by my colleague Radoslav should help you if you are using AJAX for this grid already.

Regards,

Marin Bratanov
Telerik by Progress
Try our brand new, jQuery-free Angular 2 components built from ground-up which deliver the business app essential building blocks - a grid component, data visualization (charts) and form elements.
Tags
Grid
Asked by
M
Top achievements
Rank 1
Answers by
Shinu
Top achievements
Rank 2
M
Top achievements
Rank 1
Jaime
Top achievements
Rank 1
Manish
Top achievements
Rank 2
Radoslav
Telerik team
Payal
Top achievements
Rank 1
Isaac
Top achievements
Rank 1
Pronobesh
Top achievements
Rank 1
Marin Bratanov
Telerik team
Share this question
or