我想在文本框中使用自动填充功能显示建议的字词。例如,我键入Tod ...我的数据库中以“tod”开头的所有单词都会显示但是在我选择了一个单词后,如果我输入另一个单词,如“was”,则下面没有建议的单词。可能是因为字符串集合没有“今天是”。我想展示仅以“是”而非“今天是”开头的建议词。我正在制作一个项目来预测最频繁使用的单词。这是我的代码
public partial class Form1 : Form
{
string[] arr = new string[] { "sn k", "sn k", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sept", "Oct", "Nov", "Dec" };
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void txtInput_TextChanged(object sender, EventArgs e)
{
predict();
}
void predict()
{
txtInput.AutoCompleteMode = AutoCompleteMode.Suggest;
txtInput.AutoCompleteSource = AutoCompleteSource.CustomSource;
AutoCompleteStringCollection col = new AutoCompleteStringCollection();
col.AddRange(arr);
txtInput.AutoCompleteCustomSource = col;
}
}
}
答案 0 :(得分:0)
所以一个基本的"滚动你自己"解决方案将如下工作:
string[] arr = new string[] { "sn k", "sn k", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sept", "Oct", "Nov", "Dec" };
private ListBox autoListBox;
private void Form1_Load(object sender, EventArgs e)
{
this.txtInput.TextChanged += txtInput_TextChanged;
CreateAutocompleteListBox();
}
private void txtInput_TextChanged(object sender, EventArgs e)
{
showAutoCompleteList();
}
private void CreateAutocompleteListBox()
{
this.autoListBox = new ListBox()
{
Left = this.txtInput.Left,
Top = this.txtInput.Top + this.txtInput.Height,
Width = 100,
Height = 75
};
this.autoListBox.Click += autoListBox_Click;
this.autoListBox.KeyDown += autoListBox_KeyDown;
this.autoListBox.Visible = false;
this.Controls.Add(this.autoListBox);
}
private void autoListBox_Click(object sender, EventArgs e)
{
AutocompleteFinished();
}
private void autoListBox_KeyDown(object sender, KeyEventArgs e)
{
var finishCodes = new List<Keys> { Keys.Return, Keys.Space };
if (finishCodes.Contains(e.KeyCode))
{
AutocompleteFinished();
}
}
private string GetLastWord(TextBox txt)
{
return (" " + txt.Text).Split(' ').LastOrDefault() ?? "";
}
private void showAutoCompleteList()
{
this.autoListBox.Left = this.txtInput.Left;
this.autoListBox.Top = this.txtInput.Top + this.txtInput.Height + 2;
var lastWord = GetLastWord(this.txtInput);
this.autoListBox.Items.Clear();
this.autoListBox.Items.AddRange(this.arr.Where(aw => aw.ToLower().StartsWith(lastWord.ToLower())).ToArray());
this.autoListBox.Visible = true;
}
private void txtInput_KeyDown(object sender, KeyEventArgs e)
{
// These keys show auto-complete selector
var activatorCodes = new List<Keys> { Keys.Up, Keys.Down };
if (activatorCodes.Contains(e.KeyCode))
{
SwitchToAutoCompleteList();
}
}
private void SwitchToAutoCompleteList()
{
this.autoListBox.Focus();
this.autoListBox.SelectedIndex = 0;
}
private void AutocompleteFinished()
{
var lastWord = GetLastWord(this.txtInput);
var nextWord = this.autoListBox.Text;
this.txtInput.Text = this.txtInput.Text.Substring(0, this.txtInput.Text.Length - lastWord.Length);
this.txtInput.AppendText(nextWord);
this.autoListBox.Visible = false;
}
这应该做你想要的,它会显示每个单词的自动完成!人们可以添加一些技巧,例如在文本移动时移动自动完成框。