CheckedListBox throws “Out of Memory Exception” When Adding New Items

I was using WinForm’s CheckedListBox control a few minutes ago and my application was crashing with an out of memory exception. This was happening on the line where new items were being added to the CheckedListBox. It did not make any sense at all, since I was only adding the second item to the control. Also, I was pretty sure I wasn’t being even close to running out of memory! 😀

By some happy coincidence, I figured out what the problem was. Some of the items I was adding to the list would return null in their ToString() method. Turned out that was what was causing the exception. I simply made sure that ToString() would not return null values and that solved the issue. .NET can sometimes be stupid 😀

I guess it is advisable to always write the ToString() methods with a blank string as the starting point (eg. return "" + this.ID so that it wouldn’t break in case ID is null).

Leave a Reply

Your email address will not be published.