Logan B. Lehman
Logan B. Lehman

Reputation: 5007

Setting Default Boolean Value for a Checked CheckBoxField

I have a GridView in ASP.NET with a CheckBoxField column that is bound to a DataField from a query in a database. I need to be able to have it checked if the value is false, and unchecked if the value is true.

This a little non-standard as it completely backwards on how majority of checkbox controls work, but is there a way to do this?

Upvotes: 3

Views: 1181

Answers (1)

Hanlet Escaño
Hanlet Escaño

Reputation: 17380

There are multiple approaches to this. You can try this:

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        foreach (Control ctrl in e.Row.Cells[0].Controls)
        {
            if (ctrl.GetType().Name == "CheckBox")
            {
                CheckBox chk = (CheckBox)ctrl;
                chk.Checked = !chk.Checked;
            }
        }
    }
}

Remember to add the correct cell where your checkboxfield is.

Another would be to add a TemplateField:

<asp:TemplateField>
    <ItemTemplate>
        <asp:CheckBox ID="CheckBox1" runat="server" 
            Checked='<%# !Convert.ToBoolean(Eval("Status")) %>' />
    </ItemTemplate>
</asp:TemplateField>

You could also modify your datasource after it is fetched from the database server, thus you don't need to modify your query if you are using it in a normal way in other places. Say you have a Generic List of your items:

myItems.ForEach(item => item.Status = !item.Status);

Extra jQuery version:

<script>
    $(function () {
        $("#<%=GridView1.ClientID %> input[type='checkbox']").each(function () {
            $(this).prop("checked", !$(this).prop("checked"));
        });
    });
</script>

Upvotes: 2

Related Questions