Just Code‎ > ‎

C# Asp.Net - Get Id from gridview, use it to get a file from database and upload it to the user

posted Feb 14, 2010, 3:53 AM by Peter Henell

protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        String DownloadFileName;
        int length;
        String type;
        byte[] data;


        System.Web.UI.WebControls.DataKey datak;
        datak = GridView1.DataKeys[Convert.ToInt32(e.CommandArgument)];

        using (SqlConnection con = new System.Data.SqlClient.SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["homeConnectionString"].ToString()))
        {
            using (SqlDataAdapter adapter = new System.Data.SqlClient.SqlDataAdapter("select * from projektfil where filId = @filid", con))
            {
                System.Data.DataSet ds = new System.Data.DataSet();
                con.Open();
                adapter.SelectCommand.Parameters.AddWithValue("@filId", System.Convert.ToInt32(datak.Values["filId"]));
                adapter.Fill(ds);

                DownloadFileName = ds.Tables[0].Rows[0]["name"].ToString();
                length = Convert.ToInt32(ds.Tables[0].Rows[0]["length"]);
                data = (byte[])ds.Tables[0].Rows[0]["data"];
                type = ds.Tables[0].Rows[0]["type"].ToString();
            }
        }

        Response.Clear();
        Response.ContentType = type;
        if (DownloadFileName != "")
        {
            Page.Response.AddHeader("content-disposition", "attachment; filename=" + DownloadFileName);
        }
        Response.OutputStream.Write(data, 0, length);
        Response.End();
    }
Comments