Tina
Tina

Reputation: 71

how to bind checkbox value from datatable in gridview

I need to figure out how to bind a CheckBox value in a GridView, I have written CheckBox.Checked= DataBinder.Eval(Container.DataItem, "IsSubscribed") in GridView, but the CheckBox is always checked, even when IsSubscribed is false.

I have bound the grid in Page_Load, before the page has posted back. Here is my code:

<asp:TemplateField HeaderText="Select"> 
     <ItemTemplate> 
        <asp:CheckBox 
            ID="chkIsSubscribed" runat="server" HeaderText="IsSubscribed" 
            Checked='<%# DataBinder.Eval(Container.DataItem, "IsSubscribed") %>'/>  
     </ItemTemplate> 
</asp:TemplateField>

Thanks.

Upvotes: 7

Views: 43608

Answers (3)

Philippe
Philippe

Reputation: 41

Eval() give an object type. So you have to use Eval(..).ToString() if you want to compare it... Like:

        <asp:TemplateField HeaderText="Actif">
            <ItemTemplate><asp:CheckBox ID="chkIsACTIF" runat="server" Enabled="false" Checked='<%# (Eval("ACTIF").ToString() == "1" ? true : false) %>' /></ItemTemplate>
            <EditItemTemplate><asp:CheckBox ID="chkACTIF" runat="server" Checked='<%# (Eval("ACTIF").ToString() == "1" ? true : false) %>' Enabled="true" /></EditItemTemplate>
            <FooterTemplate><asp:CheckBox ID="chkNewACTIF" runat="server" Checked="true" /></FooterTemplate>
        </asp:TemplateField>

Upvotes: 4

rahularyansharma
rahularyansharma

Reputation: 10777

<asp:TemplateField HeaderText="Select"> 
     <ItemTemplate> 
        <asp:CheckBox 
          ID="chkIsSubscribed" runat="server" HeaderText="IsSubscribed" 
          Checked='<%#Convert.ToBoolean(Eval("IsSubscribed")) %>'/>  
     </ItemTemplate> 
</asp:TemplateField>

please use this......

Upvotes: 13

Icarus
Icarus

Reputation: 63970

Put this code as your Item Template element:

<asp:TemplateField HeaderText="Select">
    <ItemTemplate>
        <asp:CheckBox ID="chkIsSubscribed" runat="server" HeaderText="IsSubscribed" 
        Checked='<%#bool.Parse(Eval("IsSubscribed").ToString())%>' />
    </ItemTemplate>
</asp:TemplateField>

Upvotes: 18

Related Questions