C # Winforms: Add "Select from list ...", fill in tab with list of bindings

I have a combobox that has the same binding:

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

It works fine, but it preselects the first value of the database. I want combobox to be preselected with some placeholder, such as "Select an item from the list ..."

What is the best way / approach to do this?
a) Adding to data Variable is an empty element
b) By setting it through property variables combobox? If so, which ones?
c) Other

+4
source share
2 answers

I found a solution for this here

Code for this:

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;
    }

And then you can just use it like this:

SetCueText(comboBox, "text");

.

+3

" ..."

0

All Articles