Click here to Skip to main content
15,881,599 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
I am trying to download a file from database using linkbutton of a gridview, but its giving me an error stating Conversion faild when converting the nvarchar file to data type int.. Here are my entities:

I have 3coulmns in my database- SaleID & SaleFilename(this coulmn stores files & their names), SaleName(This column Stores the same files in bytes)


I am trying to download a file from database using linkbutton of a gridview, but nothing is happening niether its giving me an error nor the file is bieng downloaded. Here are my entities:

I have 3coulmns in my database- SaleID & SaleFilename(this coulmn stores files & their names), SaleName(This column Stores the same files in bytes)

Here is by .aspx code:

XML
<asp:TemplateField HeaderText="SaleName" SortExpression="SaleName">
                                <ItemTemplate>
                                    <asp:LinkButton ID="LinkButton1" runat="server"CommandName="Download" CommandArgument='<%# Bind("SaleFileName") %>' Text='<%# Bind("SaleName") %>' ></asp:LinkButton>
                                </ItemTemplate>
                            </asp:TemplateField>


Here is my Code Behind File:

C#
protected void gridContributions_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName == "Download")
        {
      // make sure fileName  contains only file name like 'test.pdf'
            string fileName = Convert.ToString(e.CommandArgument);

            // make sure filePath  contains file path like 'Uploads/Scheme/test.pdf'

             string filePath = e.CommandArgument.ToString();


            string connectionString = WebConfigurationManager.ConnectionStrings["ConnectionString2"].ConnectionString;
            // SqlConnection con = new SqlConnection(connectionString);

            byte[] bytes;
            //string ContentType;

            using (SqlConnection con = new SqlConnection(connectionString))
            {
                using (SqlCommand cmd = new SqlCommand())
                {
                    cmd.CommandText = "select SaleFileName from Sales";
                    cmd.Parameters.AddWithValue("@SaleFileName", SqlDBType.NVarChar );
                    cmd.Connection = con;
                    con.Open();
                    using (SqlDataReader sdr = cmd.ExecuteReader())
                    {
                        sdr.Read(); //Here is throwing an exception saying Conversion faild when converting the nvarchar file to data type int.
                        bytes = (byte[])sdr["SaleFileName"];

                    }
                    con.Close();
                }
            }
            Response.Clear();
            Response.Buffer = true;

            // Read the original file from disk
             FileStream myFileStream = new FileStream( filePath  ,FileMode.Open);
            long FileSize = myFileStream.Length;
            byte[] Buffer = new byte[Convert.ToInt32(FileSize)];
            myFileStream.Read(Buffer, 0, Convert.ToInt32(FileSize));
            myFileStream.Close();




           // // Tell the browse stuff about the file
            Response.AddHeader("Content-Length", bytes.ToString());
            //Response.AddHeader("Content-Disposition", "inline; filename=" & fileName.Replace(" ", "_"));
            Response.AddHeader("Content-Disposition", "attachment; filename=" + fileName + ";");
            Response.TransmitFile(fileName);
            Response.ContentType = "application/octet-stream";

            // Send the data to the browser
            Response.BinaryWrite(Buffer);
            Response.End();
        }
    }


Please if anybody can tell me what mistake I am making that would be great help.
Posted
Comments
goathik 9-Jun-14 15:56pm    
can you also provide the gridview header and the databinding code, please?
goathik 9-Jun-14 16:03pm    
cmd.Parameters.AddWithValue("@SaleFileName", SqlDBType.NVarChar );

i believe the error has everything to do with this line. does it happen if you remove it?
ZurdoDev 9-Jun-14 16:51pm    
The error is pretty clear, isn't it? What line of code is causing the error?
ray thomsan 9-Jun-14 17:11pm    
sdr.read is giving a error
ZurdoDev 9-Jun-14 23:10pm    
Why are you adding a parameter? You don't actually use one. What exactly are you trying to do with that sql statement?

1 solution

i) First thing i just wanted to know why you are passing the parameter to the sql query whereas it does not look like you need to pass any parameter as you are dealing with a SQL query not a stored procedure. Either keep the query in a stored procedure and retrieve value as parameter you want else pass parameter concatenating to the query itself adding a where condition if required.

Or else you do not need any parameter at all.

ii) Secondly even if you are passing the parameter with value , the way it is being called is looking like wrong here.

C#
cmd.Parameters.AddWithValue("@SaleFileName", SqlDBType.NVarChar );


As the method name suggest it expects parameters two parameters like the parameter name and the value. The first one you are passing correctly the parameter name, but the second one should be the parameter value you want to pass not the datatype here. Please check this.

Please check with below references :-
1. Simple ADO.NET Database Read, Insert, Update and Delete using C#.[^]

2. http://www.aspsnippets.com/Articles/Save-and-Retrieve-Files-from-SQL-Server-Database-using-ASP.Net.aspx

Hope it will be of help to you.
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900