Saturday, 28 May 2011

Blinking Text within GridView depending on some condition


The Requirement

Some the text within a GridView Row should blink, depending upon certain conditions.

Suppose I have a student table with columns sid, sname, sadd and smarks. If student mark is greater than or equal to 50, then the color of the mark within the GridView should be green else the color of the mark should be red and it should blink.

Note: It should be compatible with Internet Explorer as well as Firefox.

Code for Internet Explorer

The following JavaScript will work only for Internet Explorer:


<script type="text/javascript">
    window.onload = showdata;
    function showdata()
    {
        var gridViewCtlId = '<%=GridView1. ClientID%>';
        var grid = document.getElementById(gridViewCtlId);
        var gridLength = grid.rows.length;
        for (var i = 1; i < gridLength; i++)
        {
            elementid=grid.rows[i].cells[3];
            if(elementid.innerText>=50)
            {
               elementid.style.color = 'green';
            }
            else if(elementid.innerText < 50)
            {
                elementid.style.color = 'red';
                if(elementid.style.visibility == 'hidden')
                    elementid.style.visibility = 'visible';
                else
                    elementid.style.visibility = 'hidden';
                
            }
         }
        setTimeout('showdata()', 250);
    }
    </script>

Code for Firefox


The following code will work for Firefox

<style type="text/css">
    .blinkytext
    {
     text-decoration: blink;
    }
</style>

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            if (e.Row.RowState != DataControlRowState.Edit)
            {
                Label lbl = e.Row.FindControl("LblMarks") as Label;
                if (Convert.ToInt32(lbl.Text) >= 50)
                {
                    lbl.ForeColor = Color.Green;
                }
                else
                {
                    lbl.ForeColor = Color.Red;
                    lbl.CssClass = "blinkytext";
                }
            }
        }
    }