如何使winforms文本框自动完成正确的大小写?

时间:2015-01-15 16:06:48

标签: c# winforms autocomplete

使用带有自动完成功能的winforms文本框设置为SuggestAppend我可以输出部分字符串,其余部分将建议我使用。

如果用户输入" smi"寻找"史密斯,约翰"然后通过Tab键自动填充字符串的其余部分,然后文本框包含" smith,John"。但是,如果用户点击该名称,那么大小写是正确的。

当Tabbing接受建议时,有没有办法让自动完成功能重新大写用户输入的字符串部分?

enter image description here

按下标签会导致:

enter image description here

点击名称会导致(这就是我想要的):

enter image description here

2 个答案:

答案 0 :(得分:1)

为了处理这种情况,我处理了文本框Leave事件。我们的想法是用逗号分割文本,将结果字符串的第一个字母大写,然后将字符串重新连接在一起。

private void textBox1_Leave(object sender, EventArgs e)
{
  string[] strings = this.textBox1.Text.Split(new char[] { ',' });

  for (int i = 0; i < strings.Length; i++)
  {
    strings[i] = string.Format("{0}{1}", char.ToUpper(strings[i][0]), strings[i].Substring(1));
  }

  this.textBox1.Text = string.Join(",", strings);
}

答案 1 :(得分:1)

这是我提出的最终功能,它用文本框的AutoCompleteCustomSource中的一行替换文本框的内容(按字母顺序排序)。

所以,这仍然适用于任何情况(例如,如果用户输入“aLLeN”,它仍然会改为“Allen,Charlie(ID:104)”

private void fixContent()
{
    String text = txtAutoComplete.Text;
    List<String> matchedResults = new List<String>();

    //Iterate through textbox autocompletecustomsource
    foreach (String ACLine in txtAutoComplete.AutoCompleteCustomSource)
    {
        //Check ACLine length is longer than text length or substring will raise exception
        if (ACLine.Length >= text.Length)
        {
            //If the part of the ACLine with the same length as text is the same as text, it's a possible match
            if (ACLine.Substring(0, text.Length).ToLower() == text.ToLower())
                matchedResults.Add(ACLine);
        }
    }

    //Sort results and set text to first result
    matchedResults.Sort();
    txtAutoComplete.Text = matchedResults[0] 
}

感谢OhBeWise,我将其附加到文本框离开事件:

private void txtAutoComplete_Leave(object sender, EventArgs e)
{
    fixContent();
}

但是我还需要涵盖当按下enter,tab,left和right时接受自动完成的情况。将此附加到keydown事件不起作用,因为我认为自动完成事先捕获事件,所以我附加到previewkeydown事件:

private void txtAutoComplete_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
{
    Keys key = (Keys)e.KeyCode;

    if (key == Keys.Enter || key == Keys.Tab || key == Keys.Left || key == Keys.Right)
    {
        fixContent();
    }
}