Refreshing an ASP.NET Page following GridView DataBind

UPDATE:
It seems that the issue lies in the fact that an ASP:GridView has an OnDataBound() event in the code-behind, but the corresponding HTML table does not. To address this, I need to attach the event to JavaScript. This realization is causing some difficulty for me in resolving this particular problem. Back to square one.


Transitioning from desktop development with WinForms and VB.NET to ASP.NET has been quite a challenge for me. The concepts of DOM, JavaScript, Session State, and other web development aspects have stretched my mind. Despite conducting extensive research, including watching hours of videos and reading hundreds of pages on "Intro to ASP.NET", I still encounter hurdles with what should be simple issues.

Essentially, my current predicament can be summed up as follows:

  1. I have a page where the user initiates a lengthy process.
  2. This process can take several minutes, so I want to provide feedback to the user indicating ongoing activity.
  3. Upon completion of the process, there are two scenarios:
    a. Results to display in a GridView
    b. No results to display
  4. If there are results, I need to showcase them.
  5. If there are no results, I want to show a label stating "No results to display" to the user.

What's currently functioning:

  1. The basic page allows users to select start and end dates to initiate the process.
  2. The processing logic using LINQ-to-SQL, created for a desktop application, works well.
  3. An UpdatePanel on the page shows a label and an animated gif to indicate ongoing activity.
  4. If results are available, they are correctly displayed in the GridView.

Challenges faced:

  1. I would like to implement a progress bar to visually represent the progress made towards completion instead of relying on a continuously animating gif. While I can calculate the progress value easily, transferring this value from the server to the webpage poses a challenge.

  2. Figuring out how to trigger an event to reveal the label is proving difficult. The long process runs within a button's click event handler, where I execute custom code and generate a DataTable saved as a session variable. After assigning it as the DataSource for the GridView and calling GridView.DataBind(), attempts to hide/reveal the label based on DataTable content yield no visible changes.

Solving Problem #2 is crucial for preparing this website for deployment. It likely involves a JavaScript solution, which I've attempted, but my efforts feel more like guesswork without a clear understanding of the optimal solution.

Below is the label I aim to selectively reveal/make visible:

<tr>
    <td colspan="2" align="center">
        <h2><asp:Label runat="server" ID="lblNoMissing" Text="No Missing Documentation Found" Visible="false"></asp:Label></h2>
    </td>
</tr>

Here is a JavaScript function I am experimenting with:

<script type="text/javascript">
    function databound() {
        var gridViewID = '<%=_gridView1.ClientID%>';
        var labelID = '<%=lblNoMissing.ClientID%>';
        var gridView = document.getElementById(gridViewID);
        if (gridView.rows.length > 0) {
            $get(labelID).style.visibility = "false";
        } else {
            $get(labelID).style.visibility = "true";
        }
    }
</script>

Error Encountered: Failure message reads: (databound not a member of Default.aspx)

<asp:GridView ID="_gridView1" runat="server"
    AllowSorting="True" AutoGenerateColumns="False" CellPadding="4" 
    ForeColor="#333333" GridLines="Horizontal" PageSize="20" OnDataBound="databound();">
// Rest of GridView definition removed
</asp:GridView>

What step am I missing here?

Your assistance is greatly appreciated!

Answer №1

When dealing with issue #1, there are numerous Javascript progress bars that can be used for free. If you're having trouble retrieving a specific value, consider implementing the following HTML code:

<asp:Label ID="ProgressValue" runat="server" visible="false" /> 

Then, in your code behind, assign the value from your database to ProgressValue.Text. This way, you can reference it in your JavaScript.

As for your second challenge, have you considered adding the following C# code in your code behind?

// Process here
if(IDofGridView.Rows != null) 
{
    lblNoMissing.Visible = true; 
}

Are there any missing details or steps that need to be addressed?

Answer №2

To achieve task #2, change the style.visibility attribute to "visible" Refer to: http://www.w3schools.com/cssref/pr_class_visibility.asp for a list of valid values.

For task #1, consider utilizing an update panel with a timer for automatic refresh. The server can update the user's session with the current status. The update panel code then retrieves the session info and displays it accordingly.

Answer №3

After much trial and error, I have come up with a working solution for a problem I was facing. Here's a breakdown of what I did:

  1. I decided to put my initial plans on hold for now as I couldn't spare the time to delve deeper into the issue. It's disappointing because it seems like a common need, yet finding a straightforward solution proved to be elusive. Perhaps there's some crucial information missing that would simplify things.

  2. I had a GridView, a progress Label, an animated gif, and a "no results" Label that needed to be shown or hidden at different times. What worked for me was placing them within UpdatePanels and toggling their visibility in the code-behind. However, I encountered a hurdle when attempting to change the visibility of a control located outside an UpdatePanel from code initiated inside one. It felt like crossing a barrier that was impossible. When the "no missing" Label was situated outside the UpdatePanel, the lengthy process triggered by a button inside couldn't alter its visibility. (Does this make sense? Any corrections welcome.)

Thank you for taking the time to read this and for any suggestions!


Edit:
Upon further investigation, I realized that the code handling the show/hide functionality of my Label and GridView was independent of the long-running process executed in the code-behind file.

Here's the snippet in Default.aspx that achieves the desired outcome:

<script type="text/javascript" >
Sys.WebForms.PageRequestManager.getInstance().add_initializeRequest(CheckStatus);

function CheckStatus(sender, args) {
    var prm = Sys.WebForms.PageRequestManager.getInstance();

    if (prm.get_isInAsyncPostBack()) {
        args.set_cancel(true); // prevent request from being sent
        $get("_messageSpan").innerHTML = "<h2>The last request is still processing.</h2>";
    }
    else {
        var lbl = document.getElementById('<%=lblNoMissing.ClientID%>');
        if (lbl) {
            lbl.style.visibility = "hidden";
        }
        var gview = document.getElementById('<%=_gridView1.ClientID%>');
        if (gview) {
            gview.style.visibility = "hidden";
        }
        $get("_messageSpan").innerHTML = "";
    }
}
</script>

The section concerning "_messageSpan" aims to prevent subsequent button clicks from triggering the long-running process again and inform users of its ongoing execution. Now, with the correct behavior set up, my page functions as intended. While the code may not be elegant, it serves its purpose well!

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

Display the div only if the content matches the text of the link

Looking for a way to filter posts on my blog by category and display them on the same page without navigating away. Essentially, I want users to click on a specific tag and have all posts with that tag show up. Since the CMS lacks this functionality, I pla ...

Incorporating unique numbers in the map reduce process

I have a CSV file containing information on which numbers called each other and the details of the calls like duration, time, etc. My goal is to compile all the numbers that a specific number has called into an array. Each element in this array should be ...

Guidelines for recompiling a directive after it has been added to the DOM (angularjs)

After successfully creating a directive, let's call it <calendar></calendar> It displays as intended and functions correctly. However, my current dilemma is how to (re)render it once it has been added to the DOM. Constantly having it on ...

We're sorry, but it seems like the page you are looking for can't be found

I am currently learning Next.js and I have been attempting to navigate to a component in Next.js using the Link component. Can anyone please provide guidance on how to properly achieve this? I am encountering a "404 Page Not Found" error when trying to do ...

What is the best way to display the overall score following each quiz within the (Summary Table) GridView?

In my company, I have a GridView displaying the total number of participants in each quiz for every division. Now, I want to calculate the sum of these numbers and include a new row showing the overall total of participants from all divisions after each qu ...

Converting JSON to a list using JavaScript

As a beginner in JavaScript, I apologize for asking possibly a redundant question. Can someone guide me on the most effective way to parse json? I am specifically interested in extracting a list of strings under the name Maktg: { "d":{ "res ...

Find the intersection of objects near the Raycaster in Three.js

Having trouble getting the objects that are considered 'near' the mouse using the following method: raycaster.near = 10; raycaster.far = 100; var intersects = raycaster.intersectObjects( scene.children ); if ( intersects.length > 0 ) { ...

Error 500 occurs during an ajax call to the server, however, the call works fine when running on localhost

I encountered an issue with my JavaScript code when making an AJAX call to a specific server. The strange thing is that it works perfectly fine when I use localhost, but as soon as I try calling the service from the uploaded server, I get an ERROR 500. T ...

Developing user registration and authentication using Backbone.js in conjunction with Django Rest Framework

In the process of developing my app, I am utilizing backbone.js for the frontend and django-rest-framework for the backend. My goal is to enable user registration, login, logout functionality, and be able to verify whether a user is logged in using backbon ...

Ensure the validation of numerous input fields within a single form with the use of Vue 3 composition API

Within my application, I have implemented custom validation and validators to ensure the accuracy of various form fields. The submit button functionality is designed to remain disabled until all input fields are filled. The creation of validators involves ...

Changing the color of the timePicker clock in material-ui: a step-by-step guide

I have been attempting to update the color of the time clock in my timeInput component (material-ui-time-picker) for material-ui, but unfortunately, it is not reflecting the change. Here is the code I am using: <TimeInput style ={heure} ...

Animating the Bookmark Star with CSS: A Step-by-Step Guide

I found this interesting piece of code: let animation = document.getElementById('fave'); animation.addEventListener('click', function() { $(animation).toggleClass('animate'); }); .fave { width: 70px; height: 50px; p ...

Tips on incorporating inline CSS within master pages

I am facing a dilemma with my master page that includes an external CSS file in the header. While most of the pages have the same height, only one page needs to be longer. Instead of creating a new master page or modifying the existing CSS file entirely, ...

Utilizing AngularJS's ng-repeat directive in conjunction with a select input allows for seamless binding of an object

Upon receiving my get request $scope.variables = response.data; this is my select statement: <select name="varSelect" id="varSelect" ng-model="wid.adapter"> <option ng-repeat="variable in variables" value="{{variable.id}}">{{vari ...

Utilizing Dictionary<string, string> Objects for Sorting in ASP.NET 2.0 or Other Options

What is the best way to alphabetically sort a list of countries in C# 2.0 for asp.net? Are there any alternatives to using Dictionay object for this task? ...

"Exploring In-Depth Data Visualization: A Guide to Navigating Charts

It was shocking to me how scarce the information on this subject is. I have a ChartJS pie chart that I would like to delve deeper into by clicking on a slice of the pie. Do you have any suggestions on how to achieve this? ...

Determine the frequency of occurrences for each item within an array

Here is the code snippet I created: <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script> <link href="app.css" rel="stylesheet" type="text/css"/& ...

Is there a way to create a recurring Promise .then statement?

Is there a way to create a loop with a repeated .then clause? I need to continue executing the .then clause promise, and if the exit condition is not met, I have to repeat the same process until the condition is satisfied. My scenario involves making mult ...

Code executed on the server in an aspx file

Can you clarify in which stage of the Control Execution Lifecycle the "Server-Side-Code written in an aspx file" is executed? Does it occur before SaveState or after? I believe it happens during the rendering phase, is that accurate? If my code in the as ...

Using ASP.NET to Send Emails

I am currently developing a Flight booking system and I am looking for a way to email users their E-Ticket which contains all the necessary travel information. The E-Ticket is created dynamically using the booking ID retrieved from the database and detai ...