Binding the Checked Property of a CheckBox within a TemplateItem
Asked Answered
R

5

12

For the life of me I cannot bind the Checked property of a CheckBox control within a TemplateField (declaritively).

I have tried:

<asp:TemplateField>
    <ItemTemplate>
        <asp:CheckBox ID="deactivated" runat="server" checked="<%#Eval("Deactivated")%>"></asp:CheckBox>
    </ItemTemplate>
<asp:TemplateField>

and

<asp:TemplateField>
    <ItemTemplate>
        <asp:CheckBox ID="deactivated" runat="server" checked="<%#Eval(Container.DataItem, "Deactivated")%>"></asp:CheckBox>
    </ItemTemplate>
    </asp:TemplateField>      
</asp:TemplateField>

I keep seeing a warning stating:

Cannot create an object of type 'System.Boolean' from it's string representation' 'for the 'Checked' property

What am I doing wrong?

Ralaigh answered 20/1, 2010 at 18:39 Comment(0)
H
18

It may be because of the double quotes you've used. Try:

checked= '<%# Eval("Deactivated") %>'
Hoy answered 20/1, 2010 at 18:49 Comment(2)
You are right. I won't work with the double quotes as outer quotesSteeplebush
Do you know why single quotes are required?Whirligig
F
3

Use single quotes around the property value:

<asp:CheckBox ID="deactivated" runat="server" checked='<%#Eval("Deactivated")%>'></asp:CheckBox>

Fibula answered 20/1, 2010 at 18:50 Comment(0)
D
1

It's best to handle this via code-behind in the control's rowdatabound event (assuming it's a gridview).

if (e.Row.RowType == RowType.DataRow)
{
    CheckBox chk = (CheckBox) GridView1.FindControl("deactivated");
    chk.Checked = true;
}

Note: The abv code may contain errors ...

OR,

Retrieve the data in such a manner that that particular field the checkbox is trying to bind to should be a field of type bit (i.e. it can either have 1 or 0).

Denman answered 20/1, 2010 at 18:48 Comment(0)
A
1

This is a pretty old question, but here's what I had to do in VS2013, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35

<asp:TemplateColumn ItemStyle-Width="50" HeaderText="Is Verified">
  <ItemTemplate>
    <asp:CheckBox ID="chkVerified" runat="server" AutoPostBack="true" EnableViewState="true" OnCheckedChanged="chkVerified_CheckedChanged" Checked='<%#DataBinder.GetPropertyValue(Container.DataItem,"IsVerified").ToString()=="0"%>' />

                        </ItemTemplate>
</asp:TemplateColumn>

because my property was not boolean.

Arette answered 6/2, 2014 at 20:34 Comment(0)
S
0

Eval is for evaluating expressions.

Try Bind.

checked='<%#Bind("Deactivated")%>'
Steeplebush answered 20/1, 2010 at 18:43 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.