Make checkbox of detailsview to be checked by default for insert new record?

Ahmad Z. Tibi picture Ahmad Z. Tibi · Oct 28, 2012 · Viewed 13.5k times · Source

I am using DetailsView which its DefaultMode: insert, and I want to make its checkbox to be checked by default also user can change it to unchecked, but to bind checkbox we should use

Checked='<%# Bind("Cit_Visible") %>' 

and this lets the default status of checkbox to be unchecked, so how can I solve this?

Answer

eyegropram picture eyegropram · Mar 7, 2014

When using a DetailsView data control and you have checkbox values you may be starting with an asp:CheckBoxField which handles all the display modes for you. If you want to keep the checkbox binding but also set the default to checked perhaps for an insert you can do the following.

Convert the field to a TemplateField which can be done through the design view of visual studio or manually by replacing this type of block..

<asp:CheckBoxField DataField="Information" HeaderText="Information" SortExpression="Information" />

with a block of code like this

<asp:TemplateField HeaderText="Information" SortExpression="Information">
            <EditItemTemplate>
                <asp:CheckBox ID="chkInformation" runat="server" Checked='<%# Bind("Information") %>' />
            </EditItemTemplate>
            <InsertItemTemplate>
                <asp:CheckBox ID="chkInformation" runat="server" Checked='<%# Bind("Information") %>' />
            </InsertItemTemplate>
            <ItemTemplate>
                <asp:CheckBox ID="chkInformation" runat="server" Checked='<%# Bind("Information") %>' Enabled="false" />
            </ItemTemplate>
        </asp:TemplateField>

Then to set the checkbox default value to be checked you can do this in the code-behind

Protected Sub dvInformation_PreRender(sender As Object, e As EventArgs) Handles dvInformation.PreRender
    If CType(sender, DetailsView).CurrentMode = DetailsViewMode.Insert Then
        Dim chk As Object = CType(sender, DetailsView).FindControl("chkInformation")
        If chk IsNot Nothing AndAlso chk.GetType Is GetType(CheckBox) Then
            CType(chk, CheckBox).Checked = True
        End If
    End If
End Sub

C# (Converted from VB

protected void dvInformation_PreRender(object sender, EventArgs e)
{
        if (((DetailsView)sender).CurrentMode == DetailsViewMode.Insert) {
            object chk = ((DetailsView)sender).FindControl("chkInformation");
            if (chk != null && object.ReferenceEquals(chk.GetType(), typeof(CheckBox))) {
                ((CheckBox)chk).Checked = true;
            }
        }
}

This is obviously best when the supporting database value is a non-null bit field