When a comboBox in C# is dynamically populated the comboBox appears blank until the user clicks on it to view the available items in the dropdown. Ideally, I would like to use this blank space (prior to clicking the dropdown) to be used to give the user a hint as to what s/he should do. For example, it might say something like, "Select such-and-such..." Is there a way to do this? I tried setting the Text property, but that didn't do anything. I am using Microsoft Visual C# 2008 Express Edition. Thanks.
It is called a "cue-banner". Windows Forms doesn't support it but it can be bolted on. Add a new class to your project and paste the code shown below. Compile. Drop a button and the new control from the top of the toolbox onto your form. Set the Cue property to the text you want to show. Vista or Win7 required, the cue is only visible if the combobox doesn't have the focus.
using System;
using System.Windows.Forms;
using System.Runtime.InteropServices;
public class ComboBoxEx : ComboBox {
private string mCue;
public string Cue {
get { return mCue; }
set {
mCue = value;
updateCue();
}
}
private void updateCue() {
if (this.IsHandleCreated)
SendMessageCue(this.Handle, CB_SETCUEBANNER, IntPtr.Zero, mCue ?? "");
}
protected override void OnHandleCreated(EventArgs e) {
base.OnHandleCreated(e);
updateCue();
}
// P/Invoke
private const int CB_SETCUEBANNER = 0x1703;
[DllImport("user32.dll", EntryPoint="SendMessageW", CharSet = CharSet.Auto)]
private static extern IntPtr SendMessageCue(IntPtr hWnd, int msg, IntPtr wp, string lp);
}
Add the "hint" item to the combo box:
yourComboBox.Items.Insert(0, "Select one");
then set the selected index of the combo box to 0 like this:
yourComboBox.SelectedIndex = 0;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With