我有一个像这样数据绑定(bind)的组合框:
comboBox.InvokeIfRequired(delegate
{
var data = db.GetData();
comboBox.DisplayMember = "Value";
comboBox.ValueMember = "ID";
comboBox.DataSource = data;
});
它工作正常,但它预选了第一个数据绑定(bind)值。我希望使用一些占位符预选组合框,例如“从列表中选择项目...”
最好的方法是什么?
a) 添加到数据变量空项
b) 通过 combobox
变量属性设置?如果有,是哪些?
c) 其他
最佳答案
我找到了这个 here 的解决方案
代码是:
private const int EM_SETCUEBANNER = 0x1501;
[DllImport("user32.dll", CharSet = CharSet.Auto)]
private static extern Int32 SendMessage(IntPtr hWnd, int msg, int wParam, [MarshalAs(UnmanagedType.LPWStr)] string lParam);
[DllImport("user32.dll")]
private static extern bool GetComboBoxInfo(IntPtr hwnd, ref COMBOBOXINFO pcbi);
[StructLayout(LayoutKind.Sequential)]
private struct COMBOBOXINFO
{
public int cbSize;
public RECT rcItem;
public RECT rcButton;
public UInt32 stateButton;
public IntPtr hwndCombo;
public IntPtr hwndItem;
public IntPtr hwndList;
}
[StructLayout(LayoutKind.Sequential)]
private struct RECT
{
public int left;
public int top;
public int right;
public int bottom;
}
public static void SetCueText(Control control, string text)
{
if (control is ComboBox)
{
COMBOBOXINFO info = GetComboBoxInfo(control);
SendMessage(info.hwndItem, EM_SETCUEBANNER, 0, text);
}
else
{
SendMessage(control.Handle, EM_SETCUEBANNER, 0, text);
}
}
private static COMBOBOXINFO GetComboBoxInfo(Control control)
{
COMBOBOXINFO info = new COMBOBOXINFO();
//a combobox is made up of three controls, a button, a list and textbox;
//we want the textbox
info.cbSize = Marshal.SizeOf(info);
GetComboBoxInfo(control.Handle, ref info);
return info;
}
然后你可以像这样简单地使用它:
SetCueText(comboBox, "text");
这也适用于文本框。
关于C# 窗体 : Add an "Select from list..." placeholder to databound combobox,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30622994/