ComboBox Exception: “Too many items in the combo box”

1 Comment »

The .NET ComboBox may throw a cryptic OutOfMemoryException with the following message:

Too many items in the combo box.

This poorly-worded exception results when you Add an object to the ComboBox whose ToString() method returns a null or empty string. 

To fix this error, make sure that for every object that you add to the ComboBox, the ToString() method returns a non-empty string.

Display Icons in a ListBox

No Comments »

The standard Windows Forms ListBox control is not designed to display an icon with each item.  You can modify the ListBox to handle the DrawItem event and manually draw the items and their associated icons, as shown here and here

However, if you were hoping to use a standard off-the-shelf control with full icon support, your best bet is to use the ListView control.

C# TextBox Scroll to Cursor

No Comments »

To scroll a C# TextBox to the cursor/caret, it’s important that the TextBox is both visible and focused, then call the ScrollToCaret method:

textBox.Focus();
textBox.ScrollToCaret();

To scroll to the bottom/end of a TextBox, set the SelectionLength to 0 to remove any selection, then set SelectionStart to the end of the text in the TextBox:

textBox.SelectionLength = 0;
textBox.SelectionStart = textBox.Text.Length;
textBox.Focus();
textBox.ScrollToCaret();

DataGridView HideSelection to Hide Selection when Grid Loses Focus

3 Comments »

The DataGridView is a powerful grid control included in the .NET Framework.  One function missing, however, is the ability to hide the current selection when the DataGridView control is not focused.  What the DataGridView class needs is a HideSelection property, similar to the ListView and TextBox.  But the .NET designers have not included this capability in the DataGridView class.

Read the rest of this entry »

Display an RTF File that’s a C# Embedded Resource

2 Comments »

It’s easy to display an RTF file — that was embedded as a resource in a C# program — in a Windows Form RichTextControl.

Read the rest of this entry »

Manipulating Controls Across Threads

11 Comments »

Methods that affect a Windows Forms control can be executed only on the thread that created the control. .NET does not permit directly manipulating controls across threads. The Visual Studio compiler under .NET 2.0 will mark these attempts as errors. .NET 1.1 will allow them, but these will often result in unexpected behavior like incorrectly-painted controls.

Read the rest of this entry »