I am developing a Winform and I need a checkedlistbox. I have the values stored in an object which has a List property:
public static class Fields
{
public static IList<string> FieldList { get; set; }
static Fields()
{ ...//populate FieldList }
}
Now I would like my CheckedListBox to use Fields.FieldList as datasource. After searching online I found I needed to set
//in myForm_Load
mycheckedListBox.DataSource = Fields.FieldList;
But myCheckedListBox does not have a DataSource property.
Am I missing something here?
Here is how I am binding a
List<T>
ofUser
objects into CheckedListBox.Of course this is not recommended, since documentation is telling us that this property is hidden.
The code above works, but I noticed some side effects in Visual Studio 2012 such as:
Delay for rendering checked marker:
After you click on the desired item, there is annoying delay to render the "checked" marker.
In my case,
CheckOnClick
property is True,CausesValidation
is False.This can be worked around by iterating through your would-be datasource and adding its items one-at-a-time. For example:
This, which will cause an exception:
Can be modified to this:
I know this is pretty old; for the benefit of anyone who still has the same requirement, here's what worked for me. Note that I did not use
DisplayMember
orValueMember
properties, as it seems like it is discouraged (see @David Stratton's post above).Per the documentation, it should have this property... http://msdn.microsoft.com/en-us/library/system.windows.forms.checkedlistbox.datasource(VS.90).aspx
However, I also had the same issue on a project a while back, and used this CodeProject article to code the solution in the one project where I needed this feature.
Researching a bit more, I did find this:
http://connect.microsoft.com/VisualStudio/feedback/details/115199/checkedlistbox-datasource-displaymember-valuemember-are-hidden
Edit: The above link is no longer working, but the exceprt below is from the article that once resided there.
That explains why the property exists, but doesn't show in Intellisense.
This blog post is worth a read as well: http://waxtadpole.wordpress.com/2009/10/12/assigning-custom-class-to-checkedlistbox-datasource/
Personally I use a
DataGridView
that is bound to aDataTable
that has a Boolean field along with a field for the display value.If you hide the column headers and row headers then you get something pretty close to what a
CheckedListBox
gives you.I solved the problem by changing the ToString () method to the name that should appear:
and turning into array list with objects: