工程师要求一个数字从500到-500的组合框(负数列在底部,所以不是按字母顺序排列的)。
他们还要求能够在组合中输入数字以跳转到正确的项目。
问题:输入"44",制表符离开。然后用鼠标单击控件,您可以看到"449"被选中。
以下是完整的代码:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace combotest
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
for (int i = 500; i > -500; i--)
{
comboBox1.Items.Add(i.ToString());
}
}
private void comboBox1_Leave(object sender, EventArgs e)
{
comboBox1.SelectedIndex = comboBox1.FindStringExact(comboBox1.Text);
}
}
}
没关系!我告诉自己。FindStringExact 正在查找第一个 alpha 匹配项。所以我用循环替换了 Leave 事件代码:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace combotest
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
for (int i = 500; i > -500; i--)
{
comboBox1.Items.Add(i.ToString());
}
}
private void setCombo(string value)
{
comboBox1.Items.Clear();
int myindex = -1;
for (int i = 500; i > -501; i--)
{
myindex += 1;
comboBox1.Items.Add(i.ToString());
if (i.ToString().Trim() == value.Trim())
{
comboBox1.SelectedIndex = myindex;
}
}
}
private void comboBox1_Leave(object sender, EventArgs e)
{
// comboBox1.SelectedIndex = comboBox1.FindStringExact(comboBox1.Text);
setCombo(comboBox1.Text);
}
}
}
我再试一次,当我在输入"44"并按 Tab 键离开后单击组合上的鼠标时,仍然选择了"449"。
由于您填充ComboBox
的方式,449 在列表中出现的时间比 44 早,因此它首先被选中(它是与用户键入的内容最接近的第一个匹配项)。要获得所需的行为,您必须有两个列表 - 一个从 0 到 500,另一个从 0 到 -500。
相反,请使用NumericUpDown
框并将 Maximum
属性设置为 500,将Minimum
值设置为 -500。这将确保用户只能输入指定范围内的数字。
我只是建议
- 将自动完成源启用为 true
- 然后将您在组合框中添加的相同项目添加到自动完成源
- 将自动完成模式设置为"建议追加"。
- 将组合框的值设置为"选定项"。
我不建议使用索引。