Chage LinkButton background color in GridView using Javascript onfocus

558 Views Asked by At

I am trying to change the background color of a row in gridview when the user tabs through the rows and gets focus and loses focus.

I am able to change the foreground color of a label, (just was testing this) so I believe it can be done.

I need help writing the javascript that will capture the ClientID for both the Header of the table rows.

It probably looks something like: document.getElementById("<%= ....

But I believe you have to define the grid first followed by LinkButton. Not sure how to do this part.

My code below will change a label foreground color, keep in mind I want to change the background color of the Header and Item Template.

All help is appreciated Thanks.

Here is my code:

<script type="text/javascript">
    function setheaderfocus() {
        document.getElementById("<%=Label1.ClientID %>").style.color = "Red";  //works
    }
    function setheaderblur() {
        document.getElementById("<%=Label1.ClientID %>").style.color = "Blue"; //works
    }
</script> 

<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
<title>GridView Select Example</title>
</head>
<body>
<form id="form1" runat="server">

    <asp:Label ID="Label1" runat="server" Text="Test" ></asp:Label>

    <Columns>
        <asp:TemplateField>
            <HeaderTemplate>
                 <asp:LinkButton ID="Button2" runat="server" 
                     onfocus="setheaderfocus()" 
                     onblur="setheaderblur()"                       
                     Text="New" />
            </HeaderTemplate>
            <ItemTemplate>
                 <asp:LinkButton ID="Button1" runat="server" 
                     onfocus="setrowfocus()" 
                     onblur="setrowblur()" 
                     Text="Edit" />
            </ItemTemplate>
        </asp:TemplateField>
     </Columns>

    <asp:sqldatasource id="YourSource"
    selectcommand="SELECT * FROM &quot;TBL_YOUR_DATA&quot;"
    connectionstring="<%$ ConnectionStrings:ConnectionString %>" 
    runat="server" ProviderName="<%$ YOUR_PROVIDER %>"/>

</form>
</body>
</html>
1

There are 1 best solutions below

1
On

You could achieve this with a combination of this object in JavaScript and RowDataBound event of the asp:GridView. Pseudo code.

protected void ParticipantsGrid_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if(e.Row.RowType == DataControlRowType.Header)
    {
        e.Row.Attributes.Add("onmouseover", "setfocus(this)");
        e.Row.Attributes.Add("onmouseout", "setblur(this)");
    }
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        e.Row.Attributes.Add("onmouseover", "setfocus(this)");
        e.Row.Attributes.Add("onmouseout", "setblur(this)");
    }
}

JavaScript

function setfocus(elm) {
    elm.style.color = "Red";
}
function setblur(elm) {
    elm.style.color = "Blue";
}

P.S: I am using onmouseover and onmouseout here.