c# - TextBox AutoCompleteStringCollection 建议
问题描述
我在 C# 中为文本框创建了一个带有 CustomSource 的表单:
public partial class FormLookup : Form
{
AutoCompleteStringCollection source = new AutoCompleteStringCollection();
public FormLookup()
{
InitializeComponent();
source.Add("Test");
source.Add("TestItem");
source.Add("TestValue");
this.textBox1.AutoCompleteCustomSource = source;
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
}
结果如下所示:
我正在寻找的目的是从自动建议列表中选择多个值。当用户选择第一个值时,像';'这样的分隔符 应该再次触发自动建议。
它应该如下所示:
也许 _TextChanged 方法中有一些代码/想法?是否可以在 C# 中像 pic2 一样突出显示选定的值?
欢迎您的想法!
解决方案
您需要为此要求创建自定义控件。我创建了一个类似的。发布逻辑和代码 - 希望它可以帮助您获得基本的想法。
您需要创建两个用户控件。
- 自定义控件(第二个用户控件的容器+您向我们展示的文本框)
- 标签控件(将包含标签以显示标签文本和链接标签“x”以将其删除)一起创建单个单元自定义控件的可视化。您可以在其中输入(带有下拉建议),一旦您按下 ',' ,它将创建一个标签并将其存储在其中。
这是代码。
默认情况下,自定义控件将具有以下 cnntrols
private System.Windows.Forms.FlowLayoutPanel flayoutCustomControlContainer;
public System.Windows.Forms.TextBox textBox1; //Marking this public so it can be directly accessed by external code.
这里默认flayoutCustomControlContainer
包含textBox1
。
textBox1
将有 Key Up 事件,如下所示。
private void textBox1_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Oemcomma) //we will perform this on every ',' press
{
flayoutCustomControlContainer.Controls.Remove(textBox1);
TagControl tag = new TagControl(); //creating new Tag control
tag.lblTagName.Text = textBox1.Text.TrimEnd(",".ToCharArray());
tag.Remvoed += tag_Remvoed; //subscribing "Removed" event of Tag
tag.Width = tag.lblTagName.Width + 50;
tag.Height = tag.lblTagName.Height + 5;
flayoutCustomControlContainer.Controls.Add(tag);
textBox1.Text = "";
flayoutCustomControlContainer.Controls.Add(textBox1);
textBox1.Focus();
}
}
void tag_Remvoed(object sender, EventArgs e)
{
this.flayoutCustomControlContainer.Controls.Remove((Control)sender);
textBox1.Focus();
}
自定义控件的构造函数,如您在问题中所示,
public CustomControl()
{
InitializeComponent();
source.Add("Test");
source.Add("TestItem");
source.Add("TestValue");
this.textBox1.AutoCompleteMode = System.Windows.Forms.AutoCompleteMode.SuggestAppend;
this.textBox1.AutoCompleteSource = System.Windows.Forms.AutoCompleteSource.CustomSource;
this.textBox1.AutoCompleteCustomSource = source;
}
现在,标签控制。
private System.Windows.Forms.FlowLayoutPanel flowLayoutPanel1;
public System.Windows.Forms.Label lblTagName;
private System.Windows.Forms.LinkLabel llblRemove;
链接标签,llblRemove 将具有链接标签单击事件,该事件将引发自定义控件正在列出的事件。
private void llblRemove_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
if (Remvoed != null)
Remvoed(this, EventArgs.Empty);
}
现在,在您想使用的任何地方使用此自定义控件。
我已经在 GitHub 上上传了工作示例项目。
查找链接
推荐阅读
- powershell - 如何从批处理文件以管理员权限和高优先级/实时启动进程?
- javascript - 仅使用 javascript 的文本框日期验证
- flutter - Dart 随机唯一数字
- asp.net-mvc - 在 mvc Rpoject 中找不到文件 loader.cs
- javascript - 使用 keyup 事件时,Ajax 帖子被触发两次
- python - 有没有办法在 Python 中同时执行多个 while 循环?
- java - 如何在 jdk9 的列表模块中添加 jdk.jshell
- python - 具有多重访问权限的 Django 表单
- google-apps-script - 脚本:如何将条件格式规则复制并重新应用到编辑范围?
- excel - 另存为不间断循环