【问题标题】:combobox automatically selecting a value组合框自动选择一个值
【发布时间】:2016-05-29 10:52:45
【问题描述】:

我使用 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;

}

【问题讨论】:

  • 当我设置 sender.SelectedIndex = -1 时,我无法复制此行为我得到一个空白组合框,下拉列表中有 3 个值。在循环之后,您稍后会做什么。
  • 我只是设置了控件名称,然后将此控件添加到 devex layoutcontrolItem,然后添加到 devex LayoutControlGroup,然后添加到 devex LayoutControl
  • 抱歉,我不确定我还能提供什么。我尝试将控件添加到 flowLayoutPanel,然后将控件循环到 BindCombobox 方法。甚至尝试在添加到 flp 之前创建控件并绑定它。两者都在项目集合中放置了带有项目的空白组合框,没有任何障碍。这是使用方法2。我会设置一个 DS 并以这种方式尝试,但我觉得结果是一样的。 SelectedIndex-1 应该可以工作。

标签: c# combobox selectedvalue selectedindex selectedtext


【解决方案1】:

第一个值被选中,但当您在 ​​ComboBox 类设置中没有任何变化时是默认行为

修改第二种方法:

private void BindComboBox(ComboBox sender)
{

    List<string> hiStrings = new List<string>() {"hi", "hello", "whats up"};
    sender.DataSource = hiStrings;

    sender.SelectedItem = null;
}

这给你空ComboBoxForm

此解决方案有效,我进行了测试。

一些帮助链接:

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

【讨论】:

  • 这对我不起作用:(我想不通!!感谢您的帮助!
猜你喜欢
  • 1970-01-01
  • 2012-02-29
  • 2017-04-19
  • 2012-01-24
  • 1970-01-01
  • 2011-05-27
  • 2023-04-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多