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.
+3
A:
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;
Andrew Hare
2010-03-30 21:13:27
yes, but it won't work if the ComboBox is databound...
Thomas Levesque
2010-03-30 21:42:28
I havent tried it in C# but I know in VB.Net you can still add items to the combobox even if it is databound. The trick is in the order that you insert the data (from memory you insert it before databinding).
Ryan French
2010-03-30 21:55:55
A:
Text should work really. Could you add the code you're using for population comboBox?
Hun1Ahpu
2010-03-30 21:17:30
A:
All you need to do is set an event handler. In this case a click event handler should work. Add something like this:
private void comboBox1_Click(object sender, EventArgs e)
{
comboBox1.Text = "Please select...?";
}
APShredder
2010-03-30 21:18:22
+2
A:
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);
}
Hans Passant
2010-03-30 21:33:30
+1, I had no idea this was possible... It will probably come in handy someday ;)
Thomas Levesque
2010-03-30 21:40:05
btw, your implementation prevents the user from clearing the cue, since you're not calling SendMessageCue when the string is empty...
Thomas Levesque
2010-03-30 21:42:01