我有一个带有组合框的表单,其中填充了 3 个项目。
当我添加语句时:comboBox1.Text = "A";和comboBox1.DroppedDown = true;
自动选择下拉列表的第一项:comboBox1.Text 显示“Abc”而不是“A”。
这是代码:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace testComboBox
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
comboBox1 = new ComboBox();
PopulateComboBox();
comboBox1.Location = new Point((this.Width - comboBox1.Width) / 2, 80);
this.Controls.Add(comboBox1);
comboBox1.Text = "A";
comboBox1.DroppedDown = true;
}
ComboBox comboBox1;
private void PopulateComboBox()
{
comboBox1.Items.Add("Abc");
comboBox1.Items.Add("Abcd");
comboBox1.Items.Add("Abcde");
}
private void button_Exit_Click(object sender, EventArgs e)
{
this.Close();
}
}
}
如何禁用 ComboBox 的 Items 集合中第一项的自动选择,以便comboBox1.Text 将显示“A”而不是“Abc”?
我并不是在寻找一次性解决方法。我需要一个通用解决方案。
设置此代码
comboBox1.SelectedText = null;
public Form1()
{
InitializeComponent();
comboBox1 = new ComboBox();
PopulateComboBox();
comboBox1.Location = new Point((this.Width - comboBox1.Width) / 2, 80);
this.Controls.Add(comboBox1);
comboBox1.SelectedText = "A";
comboBox1.DroppedDown = true;
comboBox1.SelectedText = null;
}
在Loathing指向的线程的帮助下,我复制了扩展类ComboBoxAutoSelectExtension,并在表单中添加了代码行:ComboBoxAutoSelectExtension.AutoSelectOff(comboBox1);
如果您从评论中的链接复制
ComboBoxAutoSelectEx
,那么您在自己的Form1
代码中唯一需要做的就是:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
comboBox1 = new ComboBox();
String text = "A";
comboBox1.Text = text;
comboBox1.Select(text.Length,1); // put cursor at the end of text
ComboBoxAutoSelectEx.AutoSelectOff(comboBox1); // Added
PopulateComboBox();
comboBox1.Location = new Point((this.Width - comboBox1.Width) / 2, 80);
this.Controls.Add(comboBox1);
}
protected override void OnLoad(EventArgs e) { // Added
base.OnLoad(e);
comboBox1.DroppedDown = true;
}
ComboBox comboBox1;
private void PopulateComboBox()
{
comboBox1.Items.Add("Abc");
comboBox1.Items.Add("Abcd");
comboBox1.Items.Add("Abcde");
}
private void button_Exit_Click(object sender, EventArgs e)
{
this.Close();
}
}
我看不出有什么办法可以禁用项目的自动选择。我只能用之前已知的输入文本替换错误的选择。打开或关闭下拉菜单时都会发生此错误。这是打开下拉菜单时的示例代码。
// record
box_txt = comboBox1.Text;
box_pos = comboBox1.SelectionStart;
// drop down
comboBox1.DroppedDown = true;
// replace
comboBox1.Text = box_txt;
comboBox1.SelectionStart = box_pos;
我只想防止默认选择第一项。我希望组合框为空,但您仍然可以使用下拉列表作为列表值。
这解决了我的问题: 填充组合框列表后,将所选索引设置为-1,如下所示:
comboBox1.SelectedIndex = -1;
对于OP,如果您想将值设置为列表中没有的值,请执行以下操作:
comboBox1.SelectedIndex = -1;
comboBox1.Text = "A";
在我的测试中,组合框的值为“A”,该值不在下拉列表的值中。