Extend GridView cell for file preview and download

Within my gridview, there is a column labeled "File Name" which includes the names of various files. I am looking for a way to click on a specific file name and be able to view its content as well as save or download the file.

I am open to all suggestions and approaches for achieving this functionality.

_________________________________________
|                        |**file name** |
_________________________________________
|                        | a.txt        | <<----Click a.txt    
_________________________________________
|                        | b.txt        |
_________________________________________

Best regards, Vivek

Answer №1

If you want to display content in a new popup.aspx page with the filename as a query parameter, you can follow this example below:

<asp:GridView ID="FilterGrid" runat="server" AutoGenerateColumns="False" >
    <Columns>
        <asp:TemplateField HeaderText="FileName" >
            <ItemTemplate>
               <asp:HyperLink ID="ActionHyperLink" runat="server" Text='<%# Eval("FileName") %>' NavigateUrl='<%# Eval("FileName","~/FilePopUp.aspx?filename={0}") %>' Target="_blank" />
               <asp:HyperLink ID="HyperLink2" runat="server" Text='<%# Eval("FileName") %>' NavigateUrl='<%# String.Format("filepopup.aspx?filename={0}", Eval("filename")) %>' onclick="javascript:w= window.open(this.href,'DownloadFile','left=20,top=20,width=500,height=500,toolbar=0,resizable=0');return false;"></asp:HyperLink>
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>

The Page_Load method for the popup page:

protected void Page_Load(object sender, EventArgs e)
{
            if (Request.QueryString["filename"] != null)
            {
                //Retrieve content from the database
                byte[] fileContent = ....;
                Response.Clear();
                string doctype = ...;
                if (doctype == ".doc")
                {
                    Response.ContentType = "application/msword";
                }
                else if (doctype == ".pdf")
                {
                    Response.ContentType = "application/pdf";
                }
                else if (doctype == ".xls")
                {
                    Response.ContentType = "application/vnd.ms-excel";
                }
                else if (doctype == ".xlsx")
                {
                    Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
                }
                Response.BinaryWrite(fileContent);
            }
}

Answer №2

Include a link button or regular button for revealing the filename. Add a div with runat="server" to reveal the file's content.

Manage the file name button click action. When clicked, retrieve and display the file content within the div using InnerHTML property.

The instructions above apply specifically to showcasing text/html data.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

"Learn how to smoothly navigate back to the top of the page after a specified amount of time has

Just starting out with JS, CSS, and Stack Overflow! I'm currently working on a div box that has the CSS property overflow: auto. Is it possible to make the box automatically scroll back to the top after a certain amount of time when the user scrolls ...

What is the best way to retrieve JSON data in PHP that has been passed through an AJAX function?

Looking for guidance on retrieving JSON data sent via an AJAX function in PHP file. The AJAX function in question is as follows: $.ajax({ type: 'POST', url: 'data11.php', data: { json: ko.toJSON(viewModel) }, ...

Preventing an image from being repeated when using Canvas drawImage() without having to clear the entire canvas

How can I prevent multiple instances of the same image from smearing across the canvas when drawing it? The platforms seem to stick together and not separate properly. Why do I have to clear the entire rectangle for everything to disappear? Does anyone ha ...

"An Unanticipated SyntaxError occurred due to a misplaced token in the doctype declaration

I find myself revisiting a small import script, which I had to divide due to the large amount of data. Initially, there's a start.php file with an impressive ajax action and dbactions.php that handles all the heavy lifting. The script kickstarts by ...

PHP response is blank when password_hash or password_verify functions are used

My application utilizes JavaScript to retrieve a string and send it via POST to a PHP file on the server for processing. The PHP receiver is responsible for parsing the string, performing tasks, and sending back status updates to JavaScript. However, after ...

What are some ways to troubleshoot the UI of a Nativescript app?

As a newcomer to NativeScript technology, I often encounter challenges while developing applications. Whether it's troubleshooting why a textview is not displaying properly, identifying layout overlaps, or detecting other distortions in the UI, debugg ...

Unable to get md-virtual-repeat to work within md-select?

Attempting to use md-select to showcase a large amount of data is causing the browser to freeze upon opening. To address this, I tried implementing md-virtual repeat within md-select for improved performance. However, the code doesn't seem to be funct ...

use javascript or jquery to conceal the textbox control

Looking to conceal a textbox control using javascript or jquery. I attempted the following code: document.getElementsByName('Custom_Field_Custom1').style.display="none"; Unfortunately, I received an error in the java console: document.getEle ...

Extracting data from DataTables rows: A guide

I am trying to retrieve values of a row in DataTables when I click on the corresponding button, but I keep getting undefined results. Here is how the buttons are added: function getData() { $pdrs = Pdrs::select('ID_Piece', 'Designa ...

Integrating a bokeh chart within a Flask application

Upon accessing localhost:5002/simpleline via Flask, I was hoping for a straightforward bokeh plot. Instead, what I encountered was unexpected: ('', ' ') I have two essential files involved in this process. Firstly, the Python file: f ...

jquery-powered scrollable content container

<script language="javascript"> $(document).ready(function($) { var methods = { init: function(options) { this.children(':first').stop(); this.marquee('play'); }, play: function( ...

Error message: The function send() cannot be applied to the object received by request.post() in Node

As I embark on testing the functionalities of my node.js website using chai and mocha, I encountered an issue when running npm test. The error message displayed is: ' TypeError: request.post(...).send is not a function' Referencing the code sni ...

The default value in an Ionic select dropdown remains hidden until it is clicked for the first time

Having an issue with my ion-select in Ionic version 6. I have successfully pre-selected a value when the page loads, but it doesn't show up in the UI until after clicking the select (as shown in pic 2). I'm loading the data in the ionViewWillEnt ...

Error encountered in Angular CLI: Attempting to access property 'value' of an undefined variable

I am encountering an issue while trying to retrieve the values of radio buttons and store them in a MySql database. The error message I receive is TypeError: Cannot read property 'value' of undefined. This project involves the use of Angular and ...

Can file input buttons be custom styled?

Since I am using Material-UI, the traditional methods are not working for me. I have a form with two buttons positioned next to each other. One button is an "Upload File" input for users to upload a file, and the other is a submit button. I want both butto ...

React Tour displays incorrect positions when coupled with Slide transitions in Material UI Dialog

Currently, I am utilizing the react-tour library to incorporate a guidance feature into my project. The issue arises in the initial step which involves a small component within a <Dialog /> that requires highlighting. However, due to a transition ef ...

Adding Google Map V3 markers dynamically through jQuery

I have been using jquery and the Google Maps V3 API to dynamically add markers to my Google Maps. Whenever I click on the button search_button, an AJAX request is sent to the server, which returns a JSON array of LatLng values corresponding to the results. ...

Tips for incorporating additional filter criteria into a jquery script

I am currently utilizing a jQuery script to filter data based on date periods. However, I now need to include an additional filtering criteria for the "POSITION" column. Since I lack expertise in jQuery, I would rather accomplish this using plain vanilla J ...

Modifying the default error message in Yup: A step-by-step guide

What is the process for modifying the default error message to a custom error message? Specifically, my custom message. const VALIDATION_SCHEME = Yup.object().shape({ numOne: Yup.Number().required('!'), numTwo: Yup.Number() .r ...

The entire DOM refreshes when a user updates the input field

In my React component, I am managing two states: inputText and students. The inputText state tracks the value of an input field, while the students state is an array used to populate a list of student names. The issue arises when the inputText state change ...