Adr*_* K. 5 c# data-binding combobox winforms
我有一个像这样的数据绑定的组合框:
comboBox.InvokeIfRequired(delegate
{
var data = db.GetData();
comboBox.DisplayMember = "Value";
comboBox.ValueMember = "ID";
comboBox.DataSource = data;
});
Run Code Online (Sandbox Code Playgroud)
它工作正常,但会预先选择第一个数据绑定值。我希望组合框预先选择一些占位符,例如“从列表中选择项目...”。
最好的方法/方法是什么?
a)向数据中添加变量为空的项目
b)通过combobox变量属性进行设置吗?如果是这样,哪个?
c)其他
小智 5
我在这里找到了解决方案
其代码是:
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;
}
Run Code Online (Sandbox Code Playgroud)
然后你可以像这样简单地使用它:
SetCueText(comboBox, "text");
Run Code Online (Sandbox Code Playgroud)
这也适用于文本框。
| 归档时间: |
|
| 查看次数: |
1440 次 |
| 最近记录: |