Binding Checkboxlist

user240141 picture user240141 · Aug 2, 2012 · Viewed 18.2k times · Source

I need a simple way to bind the checkboxlist in asp.net /C#.

I am pulling 3 columns from database Id, Name and IsActive. Id and Name i think will be clear by its name. And IsActive will be used to show checked and unchecked box. I just want to know, can I bind the child check box values with IsActive while data binding?

E.g.

cbxlFeatures.DataSource = dt;
cbxlFeatures.DataValueField = "Id";
cbxlFeatures.DataTextField = "Name"; // something similar to this
cbxlFeatures.SomePropert= "IsActive";
cbxlFeatures.DataBind();

I know the conventional way to iterate through the items and data columns and compare and put checks. I need some easy and optimized way...

Thanks

Answer

SeaSharp picture SeaSharp · Aug 2, 2012

Try manually populating your checkboxlist instead, I believe the code below would do the trick for you.

private void PopulateCheckBoxList( List<MyClass> myClassList )
{
    foreach ( MyClass m in myClassList )
    {
        ListItem item = new ListItem( m.Name, m.Id.ToString() );
        item.Selected = m.IsActive;
        cbxlFeatures.Items.Add( item );
    }
}