Change GridView Cells colour if the cells have the Random number generated every 3 seconds in asp.net

3 min read 05-10-2024
Change GridView Cells colour if the cells have the Random number generated every 3 seconds in asp.net


Dynamically Highlight GridView Cells with Random Numbers in ASP.NET

The Challenge:

Imagine a scenario where you need to dynamically highlight cells in a GridView based on randomly generated numbers appearing within them every three seconds. This scenario poses a unique challenge: how to refresh the GridView regularly while highlighting specific cells based on constantly changing values.

Understanding the Problem:

In essence, we need a way to:

  1. Generate random numbers every 3 seconds.
  2. Update the GridView with these new random numbers.
  3. Dynamically change the color of cells containing these numbers based on a certain criteria (e.g., highlight the cell if the number is above a certain threshold).

The Code:

Here's a basic example using ASP.NET, C#, and JavaScript to achieve this functionality.

ASP.NET (ASPX):

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="GridViewDynamicHighlight.Default" %>

<!DOCTYPE html>
<html>
<head runat="server">
    <title>Dynamic GridView Highlight</title>
    <script src="Scripts/jquery-3.6.0.min.js"></script>
    <script src="Scripts/Default.js"></script>
</head>
<body>
    <form id="form1" runat="server">
        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="true" OnRowDataBound="GridView1_RowDataBound" />
    </form>
</body>
</html>

C# (ASPX.CS):

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace GridViewDynamicHighlight
{
    public partial class Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                // Populate the GridView with initial data
                List<int> data = new List<int> { 10, 20, 30, 40, 50 };
                GridView1.DataSource = data;
                GridView1.DataBind();

                // Start the timer to update the GridView
                Timer1.Interval = 3000; // 3 seconds
                Timer1.Enabled = true;
            }
        }

        protected void Timer1_Tick(object sender, EventArgs e)
        {
            // Generate random numbers
            List<int> data = new List<int>();
            Random random = new Random();
            for (int i = 0; i < 5; i++)
            {
                data.Add(random.Next(1, 100));
            }

            // Update the GridView data source
            GridView1.DataSource = data;
            GridView1.DataBind();
        }

        protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            // Highlight cells based on random number value
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                int cellValue = Convert.ToInt32(e.Row.Cells[0].Text);
                if (cellValue > 50)
                {
                    e.Row.Cells[0].BackColor = System.Drawing.Color.Yellow;
                }
            }
        }
    }
}

JavaScript (Default.js):

$(document).ready(function () {
    // Update the GridView dynamically with new random numbers
    setInterval(function () {
        $.ajax({
            type: "POST",
            url: "Default.aspx/UpdateGridView",
            success: function (data) {
                // Update the GridView with the returned data
                $('#GridView1').html(data);
            }
        });
    }, 3000);
});

Explanation:

  1. ASP.NET (ASPX): The code defines the GridView and includes necessary scripts for jQuery and our custom JavaScript function.
  2. C# (ASPX.CS): This code handles the following:
    • Populates the GridView with initial data on page load.
    • Starts a timer to update the GridView every 3 seconds.
    • Generates random numbers within the timer's tick event.
    • Updates the GridView's data source with the new random numbers.
    • Applies color highlighting to cells based on the random number value.
  3. JavaScript (Default.js): This script utilizes jQuery to refresh the GridView dynamically using an AJAX call every 3 seconds, fetching new data generated by the server-side code.

Key Insights:

  • Dynamic Updating: The key is to use the timer to refresh the GridView data periodically, ensuring that new random numbers are reflected in the view.
  • Client-side Interactions: JavaScript (with jQuery) enhances the user experience by updating the GridView seamlessly without requiring full page reloads.
  • Data Binding: The RowDataBound event in the server-side code allows you to dynamically manipulate the GridView cells' appearance after data binding.
  • Flexibility: You can customize the highlighting criteria (e.g., different color schemes, highlighting based on specific ranges, or using CSS classes).

Additional Value:

  • Real-time Data: This technique can be used for displaying real-time data, like stock prices, sensor readings, or game scores.
  • Interactive Visualizations: You can extend this concept to create more interactive visualizations, like highlighting cells based on user input or displaying charts based on the data.
  • Optimization: For better performance, you can consider using server-side updates instead of complete page refreshes, especially for larger datasets.

This example provides a solid foundation for building more complex and engaging interactive applications in ASP.NET. Remember to adapt the code to suit your specific requirements and leverage the power of dynamic data updates and client-side interactions for a richer user experience.