簡體   English   中英

如何使winforms文本框自動完成正確的大寫?

[英]How to make winforms textbox autocomplete correct capitalisation?

使用自動完成設置為 SuggestAppend 的 winforms 文本框,我可以輸入字符串的一部分,其余部分將被建議給我。

如果用戶鍵入“smi”以查找“Smith, John”,然后通過 Tab 鍵自動完成字符串的其余部分,則文本框包含“smith, John”。 但是,如果用戶單擊名稱,則大寫是正確的。

有沒有辦法讓自動完成在Tabbing接受建議時重新計算字符串輸入的部分?

在此處輸入圖像描述

按 T​​ab 會導致:

在此處輸入圖像描述

單擊名稱會導致(這就是我想要的):

在此處輸入圖像描述

為了處理這種情況,我處理了文本框 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);
}

這是我最終提出的功能,它將文本框的內容替換為文本框的 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();
    }
}
simple ;
 private void textbox_TextChanged(object sender, EventArgs e)
    {
        AutoCompleteStringCollection a = new AutoCompleteStringCollection();
        a = textbox.AutoCompleteCustomSource;

        for (int i = 0; i < a.Count; i++)
        {
            if (a[i].ToLower() == textbox.Text.ToLower())
            {
                textbox.Text= a[i].ToString();
                break;
            }
        }
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM