如何仅在用户键入@时显示自动完整文本

时间:2015-02-11 11:17:03

标签: c#

我在csharp windows应用程序中有一个datagrid。我想只在用户键入@时显示自动填充文本。就像我们在FB评论框中所做的一样。以下是我现在用于自动完成的代码

private void dgv_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs
{
 TextBox autoText = e.Control as TextBox;
 if (autoText != null)
 {
  autoText.AutoCompleteMode = AutoCompleteMode.SuggestAppend;                    
  autoText.AutoCompleteSource = AutoCompleteSource.CustomSource;
  autoText.AutoCompleteCustomSource = inputFields;
 }
}

1 个答案:

答案 0 :(得分:0)

如果我理解您的观点,则此代码可能会有所帮助:

private void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{              
     TextBox autoText = e.Control as TextBox;
     autoText.TextChanged += autoText_TextChanged;
}

void autoText_TextChanged(object sender, EventArgs e)
{
     TextBox autoText = sender as TextBox;
     if (autoText != null && autoText.Text[0] == '@')
     {
          autoText.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
          autoText.AutoCompleteSource = AutoCompleteSource.CustomSource;
          var source = new AutoCompleteStringCollection();
          source.AddRange(new string[] { "@MyValue" });
          autoText.AutoCompleteCustomSource = source;
     }
}

您应绑定新事件,然后比较TextBox值并执行您的操作。

<强>更新 将代码更改为:

private void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
     TextBox autoText = e.Control as TextBox;
     autoText.KeyPress += autoText_KeyPress;
}

void autoText_KeyPress(object sender, KeyPressEventArgs e)
{
     TextBox autoText = sender as TextBox;
     if (autoText.Text.Length == 0 && e.KeyChar == (char)Keys.Back)
     {
          autoText.AutoCompleteMode = AutoCompleteMode.None;
     }
     if (autoText.Text.Length == 0 && e.KeyChar == '@')
     {
          autoText.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
          autoText.AutoCompleteSource = AutoCompleteSource.CustomSource;
          var source = new AutoCompleteStringCollection();
          source.AddRange(new string[] { "MyValue" }); //values that should appear in the autocomplete
          autoText.AutoCompleteCustomSource = source;
          e.Handled = true;
     }
}

如果第一个输入字母是&#39; @&#39;,则Autocompelete mode会打开,如果您按下Backspace,直到文本框为空,Autocompelete Mode关掉。