how to bind a value of datasource to a checkbox in datalist with Eval()

折月煮酒 提交于 2019-12-13 21:08:38

问题


I have a datalist in my asp.net page. I bind a datasource to it in codebehind and I have a checkbox in this datalist.

 var n = from gi in DataContext.Context.GalleryImages
                join g in DataContext.Context.Galleries
                on gi.GalleryID equals g.GalleryID
                where g.UserID == UserID && gi.GalleryID==GalleryID
                select new
                {
                    GalleryID = g.GalleryID,
                    ImageDescription = gi.ImageDescription,
                    GalleryName = g.GalleryName,
                    ImageFileName = gi.ImageFileName,
                    IsAlbumImage = gi.IsAlbumImage,
                    ImageID=gi.ImageID
                };

        dlGalleryList.DataSource = n;
        dlGalleryList.DataBind();

When the "IsAlbumImage " is true the checkbox should be checked. How can I bind this property to the checkbox?


回答1:


It should be bind like:

<ItemTemplate>
    <asp:CheckBox id="MyCheckBox" runat="server"  Checked='<%#Eval("IsAlbumImage") %>' />
</ItemTemplate>



回答2:


Actually you have to ways to bind checkbox in a datalist 1- (recommended) Binding it directly from the ASP code using the Bind or Eval

<ItemTemplate>
    <asp:CheckBox id="MyCheckBox" runat="server"  Checked='<%#Eval("IsAlbumImage") %>' />
</ItemTemplate>

2- Binding it on the ItemDataBound Event

First you will add the event handler to your datalist control, and adds the Boolean value to a datakey to be used in itemdatabound event

<asp:DataList ID = "DataList1"  OnItemDataBound="DataListItemEventHandler"  DataKeys = "IsAlbumImage"/>

Then you add the C# code that bind this

protected void DataListItemEventHandler(object sender, DataListItemEventArgs e)
{
CheckBox checkbx = new CheckBox();
checkbx = (CheckBox)e.Item.FindControl("MyCheckBox");
checkbx.Checked = (bool) DataList1.DataKeys(e.Item.ItemIndex)("IsAlbumImage");
}



回答3:


Like this:

<asp:CheckBox
    ID="check"
    runat="server"
    Checked='<%# Eval("column_name").ToString().Equals("1") %>'
    />


来源:https://stackoverflow.com/questions/18555872/how-to-bind-a-value-of-datasource-to-a-checkbox-in-datalist-with-eval

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!