Set CheckBox "Checked" propery in ASP repeater

Anton Belev picture Anton Belev · Aug 22, 2012 · Viewed 15.7k times · Source

I was wondering if it's possible to set the checked propery of a checkbox, using a bool variable form the repeater's datasource?

I've tried several ways but without any success...:

<asp:Repeater ID="rpt" runat="server">
    <itemTemplate> 
       <asp:CheckBox runat="server" CssClass="checkbox"
            Checked="<%#Eval("IsDefault").ToString().ToLower()%>"
            ID="isDefaultCheckBox"/>
    </itemTemplate>
</asp:Repeater>

<asp:Repeater ID="rpt" runat="server">
    <itemTemplate> 
       <asp:CheckBox runat="server" CssClass="checkbox" 
            Checked="<%# DataBinder.Eval(Container.DataItem, "IsDefault")%>" 
            ID="isDefaultCheckBox"/>
    </itemTemplate>
</asp:Repeater>

IsDefault is a field in a class View:

public bool IsDefault

The repeater's DataSource is List.

Answer

Agustin Meriles picture Agustin Meriles · Aug 22, 2012

Another solution is handling ItemDataBound event:

<asp:Repeater ID="rpt" runat="server" OnItemDataBound="rpt_ItemDataBound">
    <itemTemplate> 
       <asp:CheckBox runat="server" CssClass="checkbox" ID="isDefaultCheckBox"/>
    </itemTemplate>
</asp:Repeater>

...

protected void rpt_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
    RepeaterItem ri = e.Item;
    var dataItem = ri.DataItem as YourClassOrInterface;
    var isDefaultCheckBox = ri.FindControl("isDefaultCheckBox") as CheckBox;
    isDefaultCheckBox.Checked = dataItem.IsDefault;
}