我使用System.Windows.Forms.ComboBox,我得到了一些奇怪的意外行为。在c#中,我正在为我的表单添加一些组合框并将它们绑定到列表。我设置的唯一字段是DataSource,ValueMember和DisplayMember。出于某种原因,在绑定到列表后,选择了第一个项目。我无法弄清楚发生了什么。
我的代码如下所示:
Control c = new System.Windows.Forms.ComboBox();
循环浏览所有控件,
if (c?.GetType() == typeof (ComboBox))
{
BindComboBox((ComboBox) c);
}
private void BindComboBox(ComboBox sender)
{
DataTable table = DataGateway.GetTables(1);
sender.DataSource = table;
sender.ValueMember = "ID";
sender.DisplayMember = "Name";
//sender.SelectedIndex = -1; I tried with this and without this
}
我也尝试了第二种方法,但同样的事情正在发生 -
private void BindComboBox(ComboBox sender)
{
List<string> hiStrings = new List<string>() {"hi", "hello", "whats up"};
sender.DataSource = hiStrings;
}
答案 0 :(得分:0)
当您在ComboBox
课程设置中没有任何变化
修改第二种方法:
private void BindComboBox(ComboBox sender)
{
List<string> hiStrings = new List<string>() {"hi", "hello", "whats up"};
sender.DataSource = hiStrings;
sender.SelectedItem = null;
}
这会让你在ComboBox
Form
此解决方案正常运行,我进行了测试。
一些帮助链接:
How to deselect the text of a combobox
测试方法:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void comboBox1_MouseLeave(object sender, EventArgs e)
{
var comboBox = sender as ComboBox;
this.TestMethod(comboBox);
}
private void TestMethod(ComboBox d)
{
var list = new List<string>() {"hi", "hello", "whats up"};
d.DataSource = list;
d.SelectedItem = null;
}
}