c# Winforms:添加"Select from list. "绑定组合框的占位符

本文关键字:quot 组合 绑定 占位符 list Select Winforms 添加 from | 更新日期: 2023-09-27 17:52:55

我有一个像这样绑定的组合框:

comboBox.InvokeIfRequired(delegate
        {
            var data = db.GetData();
            comboBox.DisplayMember = "Value";
            comboBox.ValueMember = "ID";
            comboBox.DataSource = data;
        });

它工作得很好,但是它预先选择了第一个绑定值。我希望组合框预选一些占位符,如"从列表中选择项目…"

做那件事的最好方法是什么?
a)在数据变量中添加空项
b)通过combobox变量属性设置?如果有,是哪些?
c)其他

c# Winforms:添加"Select from list. "绑定组合框的占位符

我在这里找到了一个解决方案

代码是:

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");

文本框也可以使用

只需使用Text属性并在那里写入"Select item from list…"