【问题标题】:C# ComboBox SelectedIndex is always at 0 once Items are added添加项目后,C# ComboBox SelectedIndex 始终为 0
【发布时间】:2017-04-04 15:30:30
【问题描述】:

EDIT 这与 SelectedIndex 属性无关...如果默认组合框文本为“ABCD”并且有一个以“ABCD”开头的项目,则组合框将找到该项目并选择它。 如何防止这种情况发生?

原创

当我单击ComboBox1 (Windows Forms - Visual Studio) 时,系统将在数据库中搜索要插入到ComboBox 的信息(string[,] Intel 是存储此信息的位置)。在调用Click 事件之前,ComboBoxSelectedIndex = -1 一起。这就是它将 Intel 添加到此特定组合框中的方式:

for (int Dim1 = 0; Dim1 < Intel.GetLength(0); Dim1++)
{
    ComboBox1.Items.Add(Intel[Dim1, 1]);
}

我的问题是:添加第一项后,ComboBox1.SelectedIndex 设置为0。即使我使用ComboBox1.SelectedIndex = -1;,它仍然假定它为0。与ComboBox1.SelectedValue = null;ComboBox1.Text = null; 相同。通过TextBox1.Text = ComboBox1.SelectedIndex;TextBox1.Text 将显示-1

我已经用另一个 ComboBox 完成了这项工作,它确实可以将 selectedindex 设置为 -1,并且用户将看到我想要的默认文本,它不包含在项目中 - 它可以吨。所以,我想这一定是我设置错误的一些属性。

【问题讨论】:

  • 您是否设置了组合框的DataSource 属性?这可能会导致此问题。 You cannot set the SelectedIndex of a ComboBox item to -1 if the item is a data-bound item. - msdn.microsoft.com/en-us/library/…
  • 计划变更。再次检查问题......这么简单的事情......如何防止组合框选择与文本值相关的项目?
  • 您应该显示您的组合框配置,即“默认文本”以及您可能预选选项的任何位置

标签: c# winforms combobox selectedindex


【解决方案1】:

https://docs.microsoft.com/en-us/dotnet/api/system.windows.forms.combobox.selectedindex?redirectedfrom=MSDN&view=netcore-3.1#remarks

要取消选择当前选定的项目,请将 SelectedIndex 设置为 -1。如果项目是数据绑定项目,则不能将 ComboBox 项目的 SelectedIndex 设置为 -1。

See this image:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-03-21
    • 1970-01-01
    • 1970-01-01
    • 2021-04-01
    • 2013-12-01
    • 1970-01-01
    • 2016-11-22
    • 1970-01-01
    相关资源
    最近更新 更多