C# 如何仅在用户键入时显示自动完成的文本@
我在csharp windows应用程序中有一个datagrid。我只想在用户键入@时显示自动完成文本。就像我们在FB评论框中所做的一样。下面是我现在用于自动完成的代码C# 如何仅在用户键入时显示自动完成的文本@,c#,C#,我在csharp windows应用程序中有一个datagrid。我只想在用户键入@时显示自动完成文本。就像我们在FB评论框中所做的一样。下面是我现在用于自动完成的代码 private void dgv_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs { TextBox autoText = e.Control as TextBox; if (autoText != null)
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;
}
}
如果我理解您的观点,以下代码可能会有所帮助:
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;
}
}
您应该绑定新事件,然后比较文本框的值,然后执行您的操作
更新
将代码更改为:
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;
}
}
如果第一个输入字母是“@”,则自动完成模式将打开,如果按Backspace键直到文本框为空,则自动完成模式将关闭。现在有什么问题?我们在FB评论框中是怎么做的?如果我的输入字段包含jill、jack、harry作为自动完成文本,那么只有当文本框以j或h开头时,自动完成才会出现。但在Facebook的评论框中,我会在我们输入@的地方得到用户名。我的要求是,只有当用户在文本框中的任何位置键入@时,我才需要显示一些列表,但在这里,自动完成列表将显示@MyValue或仅显示MyValue。每当我在任何位置键入@,我的自动完成显示都会出现