Autor Tópico: Download e delete de um ficheiro atraves de uma gridview  (Lida 580 vezes)

Offline fibalous

  • void
  • *
  • Mensagens: 34
Download e delete de um ficheiro atraves de uma gridview
« em: 09 de Fevereiro de 2010, 16:29 »
Boa tarde, tenho uma gridview com info de uma BD, a ideia principal é a partir da gridview utilizando link buttons conseguir fazer download ou apagar o ficheiro.

code da gridview:
<asp:GridView ID="GridView1" runat="server" DataSourceID="SqlDataSource2"
                Width="515px" onrowcommand="GridView1_RowCommand"
                AutoGenerateColumns="False" DataKeyNames="ID_Doc" >
                <Columns>
                    <asp:TemplateField HeaderText="Nome" SortExpression="nome">
                        <EditItemTemplate>
                            <%# Eval("nome") %>
                            <asp:TextBox ID="TextBox_nome" runat="server" Text='<%# Bind("nome") %>'></asp:TextBox>
                        </EditItemTemplate>
                        <ItemTemplate>
                            <asp:Label ID="Label_nome" runat="server" Text='<%# Bind("nome") %>'></asp:Label>
                        </ItemTemplate>
                    </asp:TemplateField>
                    <asp:BoundField DataField="data" HeaderText="Data de inserção"
                        SortExpression="data" />
            <asp:TemplateField HeaderText="Abrir Relatório" SortExpression="abrir">
                <ItemTemplate>
                <asp:LinkButton ID="Open" runat="server" Text="Abrir" OnClientClick="Open" />
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Apagar Relatório" SortExpression="apagar">
                <ItemTemplate>
                <asp:LinkButton ID="Delete" runat="server" Text="Apagar" OnClientClick="Delete" />
                </ItemTemplate>
            </asp:TemplateField>
                </Columns>
            </asp:GridView>

Código (C#): [Seleccione]
       protected void Open(object sender, EventArgs e)  
          {  

       
        int rowIndex = Convert.ToInt16(e.CommandArgument);        
        // Get the physical Path

        SqlConnection conn = new SqlConnection(new connectionString().getConnection());
        conn.Open();

        SqlCommand caminho = new SqlCommand("SELECT path FROM tbl_documentos WHERE nome ='" + (GridView1.Rows[rowIndex].FindControl("Label_nome") as Label).Text + "'", conn);
        SqlDataReader reader = caminho.ExecuteReader();
        reader.Read();
        string filepath = reader.GetString(0);
        reader.Close();


        //String filepath = "C:\\Documents and Settings\\tporteiro\\My Documents\\Relatorios\\Quest_Seguros_ECSI_2009.pdf";

        // Create New instance of FileInfo class to get the properties of the file being downloaded
        FileInfo file = new FileInfo(filepath);

        // Checking if file exists
        if (file.Exists)
        {
            // Clear the content of the response
            Response.ClearContent();

            // LINE1: Add the file name and attachment, which will force the open/cancel/save dialog to show, to the header
            Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name);

            // Add the file size into the response header
            Response.AddHeader("Content-Length", file.Length.ToString());

            // Set the ContentType
            Response.ContentType = ReturnExtension(file.Extension.ToLower());

            // Write the file into the response (TransmitFile is for ASP.NET 2.0. In ASP.NET 1.1 you have to use WriteFile instead)
            Response.TransmitFile(file.FullName);

            // End the response
            Response.End();
        }
       }
    private string ReturnExtension(string fileExtension)
    {
        switch (fileExtension)
        {
            case ".htm":
            case ".html":
            case ".log":
                return "text/HTML";
            case ".txt":
                return "text/plain";
            case ".doc":
                return "application/ms-word";
            case ".tiff":
            case ".tif":
                return "image/tiff";
            case ".asf":
                return "video/x-ms-asf";
            case ".avi":
                return "video/avi";
            case ".zip":
                return "application/zip";
            case ".xls":
            case ".csv":
                return "application/vnd.ms-excel";
            case ".gif":
                return "image/gif";
            case ".jpg":
            case "jpeg":
                return "image/jpeg";
            case ".bmp":
                return "image/bmp";
            case ".wav":
                return "audio/wav";
            case ".mp3":
                return "audio/mpeg3";
            case ".mpg":
            case "mpeg":
                return "video/mpeg";
            case ".rtf":
                return "application/rtf";
            case ".asp":
                return "text/asp";
            case ".pdf":
                return "application/pdf";
            case ".fdf":
                return "application/vnd.fdf";
            case ".ppt":
                return "application/mspowerpoint";
            case ".dwg":
                return "image/vnd.dwg";
            case ".msg":
                return "application/msoutlook";
            case ".xml":
            case ".sdxl":
                return "application/xml";
            case ".xdp":
                return "application/vnd.adobe.xdp+xml";
            default:
                return "application/octet-stream";
        }
   }
       protected void Delete(object sender, EventArgs e)  
          {

                int rowIndex = Convert.ToInt16(e.CommandArgument);
                SqlConnection conn = new SqlConnection(new connectionString().getConnection());  
                conn.Open();  
   
                //selecionar o caminho do ficheiro  
                SqlCommand caminho = new SqlCommand("SELECT path FROM tbl_documentos WHERE nome = '" + (GridView1.Rows[rowIndex].FindControl("Label_nome") as Label).Text + "'", conn);  
                SqlDataReader reader = caminho.ExecuteReader();  
                reader.Read();  
                string filepath = reader.GetString(0);  
                reader.Close();  
 
 
                //se o ficheiro existir no caminho ele elimina-o  
                FileInfo fileInfo = new FileInfo(filepath);  
                if (fileInfo.Exists)  
                fileInfo.Delete();  
 
               //vai apagar a informação correspondente ao ficheiro eliminado  
                SqlCommand sql = new SqlCommand("DELETE FROM tbl_documentos WHERE nome = '" + (GridView1.Rows[rowIndex].FindControl("Label_nome") as Label).Text + "'", conn);  
                sql.ExecuteNonQuery();  
                conn.Close();  
                 
             }

o problema que tenho até ao momento é não conseguir ir buscar o rowindex para usar na query....alguém me pode ajudar?  :wallbash:

ps_: convem dizer que só trabalho com asp.net à uns dias
« Última modificação: 09 de Fevereiro de 2010, 17:33 por fibalous »

Offline fibalous

  • void
  • *
  • Mensagens: 34
Re: Download e delete de um ficheiro atraves de uma gridview
« Responder #1 em: 09 de Fevereiro de 2010, 17:58 »
já agora se não souberem fazer da forma que indico em cima e souberam fazer de outra estou aberto a sugestões desde que isto fique a funcionar e a informação seja mostrada em lista como por exemplo na gridview é "possível de se fazer".

Offline fibalous

  • void
  • *
  • Mensagens: 34
Re: Download e delete de um ficheiro atraves de uma gridview
« Responder #2 em: 09 de Fevereiro de 2010, 18:21 »
alterei protected void Open(object sender, EventArgs e) para protected void Open(object sender, GridViewCommandEventArgs e) e deixou de dar erro na declaração do indexrow o problema é que continua a dar erro mas desta vez é na gridview:
ASP.qmetrics_relatorios_aspx' does not contain a definition for 'GridView1_RowCommand' and no extension method 'GridView1_RowCommand' accepting a first argument of type 'ASP.qmetrics_relatorios_aspx' could be found (are you missing a using directive or an assembly reference?)

Alguém sabe o que me está a escapar? :P desde já agradeço as respostas que sejam dadas.

Offline fibalous

  • void
  • *
  • Mensagens: 34
Re: Download e delete de um ficheiro atraves de uma gridview
« Responder #3 em: 09 de Fevereiro de 2010, 18:24 »
retirei onrowcommand="GridView1_RowCommand" da gridview, deixou de dar erro mas os linkbuttons não estão a fazer simplesmente nada.

Não levem a mal estar a postar frequentemente, é uma maneira de vos deixar a par do que já testei talvez assim se evite perder algum tempo.

Offline fibalous

  • void
  • *
  • Mensagens: 34
Re: Download e delete de um ficheiro atraves de uma gridview
« Responder #4 em: 10 de Fevereiro de 2010, 11:18 »
Segundo o que percebo (que não é nada  :D) tenho que dizer que o comando Open e o Delete vêm da GridView correcto? alguém sabe como o faço?

Offline fibalous

  • void
  • *
  • Mensagens: 34
Re: Download e delete de um ficheiro atraves de uma gridview
« Responder #5 em: 10 de Fevereiro de 2010, 12:05 »
tentei assim :

Código (C#): [Seleccione]
       protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
       {
           GridViewRow gvr = e.Row;

           switch (gvr.RowType)
           {
               case DataControlRowType.DataRow:
                   {
                       // Retrieve controls
                       LinkButton Open = gvr.FindControl("Open") as LinkButton;
                       LinkButton Delete = gvr.FindControl("Delete") as LinkButton;

                       if (Open != null)
                       {
                           Open.CommandArgument = gvr.RowIndex.ToString();
                       }

                       if (Delete != null)
                       {
                           Delete.CommandArgument = gvr.RowIndex.ToString();
                       }

                       break;
                   }
           }

       }

   
    protected void Open(object sender, EventArgs e)  
       {

        LinkButton Open = sender as LinkButton;

        int rowIndex = Int32.Parse(Open.CommandArgument);

           
        // Get the physical Path
        SqlConnection conn = new SqlConnection(new connectionString().getConnection());
        conn.Open();

        SqlCommand caminho = new SqlCommand("SELECT path FROM tbl_documentos WHERE nome ='" + (GridView1.Rows[rowIndex].FindControl("Label_nome") as Label).Text + "'", conn);
        SqlDataReader reader = caminho.ExecuteReader();
        reader.Read();
        string filepath = reader.GetString(0);
        reader.Close();


        //String filepath = "C:\\Documents and Settings\\tporteiro\\My Documents\\Relatorios\\Quest_Seguros_ECSI_2009.pdf";

        // Create New instance of FileInfo class to get the properties of the file being downloaded
        FileInfo file = new FileInfo(filepath);

        // Checking if file exists
        if (file.Exists)
        {
            // Clear the content of the response
            Response.ClearContent();

            // LINE1: Add the file name and attachment, which will force the open/cancel/save dialog to show, to the header
            Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name);

            // Add the file size into the response header
            Response.AddHeader("Content-Length", file.Length.ToString());

            // Set the ContentType
            Response.ContentType = ReturnExtension(file.Extension.ToLower());

            // Write the file into the response (TransmitFile is for ASP.NET 2.0. In ASP.NET 1.1 you have to use WriteFile instead)
            Response.TransmitFile(file.FullName);

            // End the response
            Response.End();
        }
       }
    private string ReturnExtension(string fileExtension)
    {
        switch (fileExtension)
        {
            case ".htm":
            case ".html":
            case ".log":
                return "text/HTML";
            case ".txt":
                return "text/plain";
            case ".doc":
                return "application/ms-word";
            case ".tiff":
            case ".tif":
                return "image/tiff";
            case ".asf":
                return "video/x-ms-asf";
            case ".avi":
                return "video/avi";
            case ".zip":
                return "application/zip";
            case ".xls":
            case ".csv":
                return "application/vnd.ms-excel";
            case ".gif":
                return "image/gif";
            case ".jpg":
            case "jpeg":
                return "image/jpeg";
            case ".bmp":
                return "image/bmp";
            case ".wav":
                return "audio/wav";
            case ".mp3":
                return "audio/mpeg3";
            case ".mpg":
            case "mpeg":
                return "video/mpeg";
            case ".rtf":
                return "application/rtf";
            case ".asp":
                return "text/asp";
            case ".pdf":
                return "application/pdf";
            case ".fdf":
                return "application/vnd.fdf";
            case ".ppt":
                return "application/mspowerpoint";
            case ".dwg":
                return "image/vnd.dwg";
            case ".msg":
                return "application/msoutlook";
            case ".xml":
            case ".sdxl":
                return "application/xml";
            case ".xdp":
                return "application/vnd.adobe.xdp+xml";
            default:
                return "application/octet-stream";
        }
    }
    protected void Delete(object sender, EventArgs e)  
          {

                LinkButton Delete = sender as LinkButton;

                int rowIndex = Int32.Parse(Delete.CommandArgument);
       
       
                SqlConnection conn = new SqlConnection(new connectionString().getConnection());  
                conn.Open();  
   
                //selecionar o caminho do ficheiro  
                SqlCommand caminho = new SqlCommand("SELECT path FROM tbl_documentos WHERE nome = '" + (GridView1.Rows[rowIndex].FindControl("Label_nome") as Label).Text + "'", conn);  
                SqlDataReader reader = caminho.ExecuteReader();  
                reader.Read();  
                string filepath = reader.GetString(0);  
                reader.Close();  
 
 
                //se o ficheiro existir no caminho ele elimina-o  
                FileInfo fileInfo = new FileInfo(filepath);  
                if (fileInfo.Exists)  
                fileInfo.Delete();  
 
               //vai apagar a informação correspondente ao ficheiro eliminado  
                SqlCommand sql = new SqlCommand("DELETE FROM tbl_documentos WHERE nome = '" + (GridView1.Rows[rowIndex].FindControl("Label_nome") as Label).Text + "'", conn);  
                sql.ExecuteNonQuery();  
                conn.Close();  
                 
          }

para meu azar continua sem fazer nada...penso que tenha q usar o rowcommand por aqui algures mas onde? ninguém sabe responder?

Offline fibalous

  • void
  • *
  • Mensagens: 34
Re: Download e delete de um ficheiro atraves de uma gridview
« Responder #6 em: 11 de Fevereiro de 2010, 11:31 »
já agora caso ajude está aqui o code da gridview como está de momento:
Código (ASP): [Seleccione]
<asp:GridView ID="GridView1" runat="server" DataSourceID="SqlDataSource2"
                Width="515px" AutoGenerateColumns="False" DataKeyNames="ID_Doc" OnRowDataBound="GridView1_RowDataBound" >
                <Columns>
                    <asp:TemplateField HeaderText="Nome" SortExpression="nome">
                        <EditItemTemplate>
                            <%# Eval("nome") %>
                            <asp:TextBox ID="TextBox_nome" runat="server" Text='<%# Bind("nome") %>'></asp:TextBox>
                        </EditItemTemplate>
                        <ItemTemplate>
                            <asp:Label ID="Label_nome" runat="server" Text='<%# Bind("nome") %>'></asp:Label>
                        </ItemTemplate>
                    </asp:TemplateField>
                    <asp:BoundField DataField="data" HeaderText="Data de inserção"
                        SortExpression="data" />
            <asp:TemplateField HeaderText="Abrir Relatório" SortExpression="abrir">
                <ItemTemplate>
                <asp:LinkButton ID="Open" runat="server" Text="Abrir" OnClientClick="Open" />
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Apagar Relatório" SortExpression="apagar">
                <ItemTemplate>
                <asp:LinkButton ID="Delete" runat="server" Text="Apagar" OnClientClick="Delete" />
                </ItemTemplate>
            </asp:TemplateField>
                </Columns>
            </asp:GridView>

Offline fibalous

  • void
  • *
  • Mensagens: 34
Re: Download e delete de um ficheiro atraves de uma gridview
« Responder #7 em: 11 de Fevereiro de 2010, 16:56 »
Já tentei de "n" maneiras diferentes até já optei por inventar (podia ser que funcionasse) e nada, se alguém tiver sugestões sobre como fazer isto funcionar nem que seja de maneira diferente...Eu não sei outra maneira de o fazer por isso estou aberto a sugestões  :dontgetit:

Offline fibalous

  • void
  • *
  • Mensagens: 34
Re: Download e delete de um ficheiro atraves de uma gridview
« Responder #8 em: 11 de Fevereiro de 2010, 17:26 »
Tentei atribuir um valor à Label1 dentro do code behind de cada linkbutton, e não aconteceu nada, suponho que quando clico no botão ele simplesmente não vai às funções dele. Alguém sabe como resolver isto? Obrigado
« Última modificação: 11 de Fevereiro de 2010, 17:28 por fibalous »

Offline fibalous

  • void
  • *
  • Mensagens: 34
Re: Download e delete de um ficheiro atraves de uma gridview
« Responder #9 em: 11 de Fevereiro de 2010, 17:38 »
Consegui resolver o problema vou deixar aqui o código caso alguém pretenda fazer o mesmo saber como fazelo:

aspx:
Código (ASP): [Seleccione]
<asp:GridView ID="GridView1" runat="server" DataSourceID="SqlDataSource2"
                Width="515px" AutoGenerateColumns="False" DataKeyNames="ID_Doc" OnRowDataBound="GridView1_RowDataBound" >
                <Columns>
                    <asp:TemplateField HeaderText="Nome" SortExpression="nome">
                        <EditItemTemplate>
                            <%# Eval("nome") %>
                            <asp:TextBox ID="TextBox_nome" runat="server" Text='<%# Bind("nome") %>'></asp:TextBox>
                        </EditItemTemplate>
                        <ItemTemplate>
                            <asp:Label ID="Label_nome" runat="server" Text='<%# Bind("nome") %>'></asp:Label>
                        </ItemTemplate>
                    </asp:TemplateField>
                    <asp:BoundField DataField="data" HeaderText="Data de inserção"
                        SortExpression="data" />
            <asp:TemplateField HeaderText="Abrir Relatório" SortExpression="abrir">
                <ItemTemplate>
                <asp:LinkButton ID="Open" runat="server" Text="Abrir" OnClick="Open" />
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Apagar Relatório" SortExpression="apagar">
                <ItemTemplate>
                <asp:LinkButton ID="Delete" runat="server" Text="Apagar" OnClick="Delete" />
                </ItemTemplate>
            </asp:TemplateField>
                </Columns>
            </asp:GridView>

c#:

Código (C#): [Seleccione]
    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
       {
           GridViewRow gvr = e.Row;

           switch (gvr.RowType)
           {
               case DataControlRowType.DataRow:
                   {
                       // Retrieve controls
                       LinkButton Open = gvr.FindControl("Open") as LinkButton;
                       LinkButton Delete = gvr.FindControl("Delete") as LinkButton;

                       if (Open != null)
                       {
                           Open.CommandArgument = gvr.RowIndex.ToString();
                       }

                       if (Delete != null)
                       {
                           Delete.CommandArgument = gvr.RowIndex.ToString();
                       }

                       break;
                   }
           }

       }


    protected void Open(object sender, EventArgs e)  
       {

        LinkButton Open = sender as LinkButton;

        int rowIndex = Int32.Parse(Open.CommandArgument);

           
        // Get the physical Path
        SqlConnection conn = new SqlConnection(new connectionString().getConnection());
        conn.Open();

        SqlCommand caminho = new SqlCommand("SELECT path FROM tbl_documentos WHERE nome ='" + (GridView1.Rows[rowIndex].FindControl("Label_nome") as Label).Text + "'", conn);
        SqlDataReader reader = caminho.ExecuteReader();
        reader.Read();
        string filepath = reader.GetString(0);
        reader.Close();


        //String filepath = "C:\\Documents and Settings\\tporteiro\\My Documents\\Relatorios\\Quest_Seguros_ECSI_2009.pdf";

        // Create New instance of FileInfo class to get the properties of the file being downloaded
        FileInfo file = new FileInfo(filepath);

        // Checking if file exists
        if (file.Exists)
        {
            // Clear the content of the response
            Response.ClearContent();

            // LINE1: Add the file name and attachment, which will force the open/cancel/save dialog to show, to the header
            Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name);

            // Add the file size into the response header
            Response.AddHeader("Content-Length", file.Length.ToString());

            // Set the ContentType
            Response.ContentType = ReturnExtension(file.Extension.ToLower());

            // Write the file into the response (TransmitFile is for ASP.NET 2.0. In ASP.NET 1.1 you have to use WriteFile instead)
            Response.TransmitFile(file.FullName);

            // End the response
            Response.End();
        }
       }
    private string ReturnExtension(string fileExtension)
    {
        switch (fileExtension)
        {
            case ".htm":
            case ".html":
            case ".log":
                return "text/HTML";
            case ".txt":
                return "text/plain";
            case ".doc":
                return "application/ms-word";
            case ".tiff":
            case ".tif":
                return "image/tiff";
            case ".asf":
                return "video/x-ms-asf";
            case ".avi":
                return "video/avi";
            case ".zip":
                return "application/zip";
            case ".xls":
            case ".csv":
                return "application/vnd.ms-excel";
            case ".gif":
                return "image/gif";
            case ".jpg":
            case "jpeg":
                return "image/jpeg";
            case ".bmp":
                return "image/bmp";
            case ".wav":
                return "audio/wav";
            case ".mp3":
                return "audio/mpeg3";
            case ".mpg":
            case "mpeg":
                return "video/mpeg";
            case ".rtf":
                return "application/rtf";
            case ".asp":
                return "text/asp";
            case ".pdf":
                return "application/pdf";
            case ".fdf":
                return "application/vnd.fdf";
            case ".ppt":
                return "application/mspowerpoint";
            case ".dwg":
                return "image/vnd.dwg";
            case ".msg":
                return "application/msoutlook";
            case ".xml":
            case ".sdxl":
                return "application/xml";
            case ".xdp":
                return "application/vnd.adobe.xdp+xml";
            default:
                return "application/octet-stream";
        }
    }
    protected void Delete(object sender, EventArgs e)  
          {

                LinkButton Delete = sender as LinkButton;

                int rowIndex = Int32.Parse(Delete.CommandArgument);


                SqlConnection conn = new SqlConnection(new connectionString().getConnection());  
                conn.Open();  
   
                //selecionar o caminho do ficheiro  
                SqlCommand caminho = new SqlCommand("SELECT path FROM tbl_documentos WHERE nome = '" + (GridView1.Rows[rowIndex].FindControl("Label_nome") as Label).Text + "'", conn);  
                SqlDataReader reader = caminho.ExecuteReader();  
                reader.Read();  
                string filepath = reader.GetString(0);  
                reader.Close();  
 
 
                //se o ficheiro existir no caminho ele elimina-o  
                FileInfo fileInfo = new FileInfo(filepath);  
                if (fileInfo.Exists)  
                fileInfo.Delete();  
 
               //vai apagar a informação correspondente ao ficheiro eliminado  
                SqlCommand sql = new SqlCommand("DELETE FROM tbl_documentos WHERE nome = '" + (GridView1.Rows[rowIndex].FindControl("Label_nome") as Label).Text + "'", conn);  
                sql.ExecuteNonQuery();  
                conn.Close();  
                 
          }

espero que vos sirva para projectos futuros ou projectos que tenham a decorrer.