Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 384
Logan B. Lehman Avatar asked Dec 18 '25 20:12

Logan B. Lehman


1 Answers

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>
like image 196
Hanlet Escaño Avatar answered Dec 21 '25 17:12

Hanlet Escaño



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!