Set CheckBox “Checked” propery in ASP repeater

2019-02-19 04:34发布

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.

4条回答
霸刀☆藐视天下
2楼-- · 2019-02-19 04:40

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;
}
查看更多
狗以群分
3楼-- · 2019-02-19 04:46

The problem with the code is actually the fact that you are nesting double quotes

Checked="<%# DataBinder.Eval(Container.DataItem, "IsDefault")%>"

should be

Checked='<%# DataBinder.Eval(Container.DataItem, "IsDefault")%>'
查看更多
地球回转人心会变
4楼-- · 2019-02-19 05:00

I'm fairly sure that it should work this way:

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

By the way, there's a missing < in your first approach:

Checked="%#Eval...

Edit: (since you've also edited your question and corrected it)

Now there's something else wrong, you've two consecutive quotes here:

Checked="<%#Eval("
查看更多
地球回转人心会变
5楼-- · 2019-02-19 05:01

Old question, but I solved this in my application using something much simpler:

<asp:CheckBox ID="chkIncludePdf" runat="server" Checked='<%# Eval("DefaultInclude").ToString() == "True" %>' />
查看更多
登录 后发表回答