1

I have a checkbox inside a GridView and I want to change its color to red when unchecked and to green when checked.

How can I do this ?

<ItemTemplate>
   <asp:CheckBox ID="checkboxAttendanceStatus" BackColor="Red" runat="server" AutoPostBack="true" />
</ItemTemplate>
VDWWD
  • 35,079
  • 22
  • 62
  • 79
Suyash Gupta
  • 546
  • 10
  • 31

2 Answers2

1

You can set the OnCheckChanged server-side event for the check box as in markup below. Then, all you need is to write code in server-side event to change the BackColor.

Markup

<ItemTemplate>
   <asp:CheckBox ID="checkboxAttendanceStatus" BackColor="Red" runat="server"
        AutoPostBack="true" OnCheckedChanged="checkboxAttendanceStatus_CheckedChanged"/>
</ItemTemplate>

C# code for server-side event

protected void checkboxAttendanceStatus_CheckedChanged(object sender, EventArgs e)
{
    CheckBox chk = sender as CheckBox;
    if (chk.Checked)
    {
        chk.BackColor = System.Drawing.Color.Green;
    } else
    {
        chk.BackColor = System.Drawing.Color.Red;
    }
}

Another approach using client-side code without any C#

If you wanted to implement this requirement completely on the client-side, then you could add the following JavaScript to your aspx page.

You do not need to subscribe to CheckChanged event of checkbox nor write any C# code. This approach needs only JavaScript/jQuery code.

<script type="text/javascript">
function pageLoad() {

    var checkboxes = $("[id*='checkboxAttendanceStatus']");

    checkboxes.each(function (i) {
        if (this.checked) {
            $(this).parent().css("background-color", "green");
        } else {
            $(this).parent().css("background-color", "red");
        }
    });
}
</script>
Sunil
  • 20,653
  • 28
  • 112
  • 197
  • Client-side approach is not working. How do I invoke the pageLoad() ? – Suyash Gupta Feb 15 '18 at 09:29
  • In ASP.Net, you don't have to invoke pageLoad method since ASP. Net framework will automatically invoke it once the page scripts have loaded and all objects have been created. You can read more about it at this MSDN link: https://msdn.microsoft.com/en-us/library/bb383829.aspx – Sunil Feb 15 '18 at 12:07
  • Also, make sure that jquery is included in the aspx page, else client-side approach will not work. – Sunil Feb 15 '18 at 12:09
0

The easiest way is to use CSS with an adjacent sibling selector for the label since the generated html will look like this:

<input id="id" type="checkbox" name="id" /><label for="id">Label</label>

So set the color of the label based on the checked status of the CheckBox.

<style>
    input[type="checkbox"]:checked + label {
        color: blue;
        background-color: yellow;
    }

    input[type="checkbox"] + label {
        color: red;
        background-color: green;
    }
</style>

If you want to style the actual checkbox itself, you're gonna need a jQuery plugin or more complex CSS tricks. See this answer here

VDWWD
  • 35,079
  • 22
  • 62
  • 79