【问题标题】:C# Winforms: Add an "Select from list..." placeholder to databound comboboxC# Winforms:向数据绑定组合框添加“从列表中选择...”占位符
【发布时间】:2023-03-11 17:50:02
【问题描述】:

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

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

它工作正常,但它预先选择了第一个数据绑定值。我希望使用一些占位符预先选择组合框,例如“从列表中选择项目...”

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

【问题讨论】:

  • 但是我在Items集合中没有占位符,所以SelectedValue属性中没有设置值。
  • 它需要是绑定数据中的一个值,无论您要预选哪个。 SelectedValue 属性设置器确定 SelectedIndex 需要是什么才能匹配它。
  • 好的,所以你说最好的方法是在db.GetData(); 函数中添加一个占位符项并使用它的值来设置combobox.SelectedValue
  • 哦,等等,我现在突然明白你所说的“占位符”是什么意思了。这对于绑定的组合框并不完全理想。请考虑使用cue instead

标签: c# winforms data-binding combobox


【解决方案1】:

我找到了解决这个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");

这也适用于文本框。

【讨论】:

  • 我知道这是一篇旧帖子,但是有没有办法让它适用于将 DropDownStyle 设置为 DropDownList 的组合框?它仅在设置为 DropDown 时才有效。
  • 我实施了您的建议,但发现它不起作用。适用代码为county_CB.SelectedItem = -1; SCBT.set_combobox_text (county_CB, Constants.SELECT_ONE);
【解决方案2】:

只需使用文本属性并在那里写“从列表中选择项目...”

【讨论】:

  • 我担心Text 属性将在数据绑定时被覆盖。这个方法我试过了,不行
猜你喜欢
  • 2017-11-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-26
  • 2019-08-28
相关资源
最近更新 更多