我是编程新手,我需要有关如何使用 c#应用程序中的文本框过滤列表框的帮助。
我的意思是在文本框中输入一些文本并在列表框中同时过滤如果项目在列表中退出然后选择到文本框中,则打开新表单以创建项目,请给我示例。
答案 0 :(得分:2)
这是一个简单的自动填充文本框,您应该可以使用它来满足您的需求:
class AutoSuggestControl : TextBox
{
List<string> Suggestions;
int PreviousLength;
public AutoSuggestControl() : base()
{
Suggestions = new List<string>();
// We keep track of the previous length of the string
// If the user tries to delete characters we do not interfere
PreviousLength = 0;
// Very basic list, too slow to be suitable for systems with many entries
foreach(var e in yourListbox.Items)
{
//add your listbox items to the textbox
}
Suggestions.Sort();
}
/// <summary>
/// Search through the collection of suggestions for a match
/// </summary>
/// <param name="Input"></param>
/// <returns></returns>
private string FindSuggestion(string Input)
{
if (Input != "")
foreach (string Suggestion in Suggestions)
{
if (Suggestion.StartsWith(Input))
return Suggestion;
}
return null;
}
/// <summary>
/// We only interfere after receiving the OnTextChanged event.
/// </summary>
/// <param name="e"></param>
protected override void OnTextChanged(EventArgs e)
{
base.OnTextChanged(e);
// We don't do anything if the user is trying to shorten the sentence
int CursorPosition = SelectionStart;
if (Text.Length > PreviousLength && CursorPosition >= 0)
{
string Suggestion = FindSuggestion(Text.Substring(0, CursorPosition));
if (Suggestion != null)
{
// Set the contents of the textbox to the suggestion
Text = Suggestion;
// Setting text puts the cursor at the beginning of the textbox, so we need to reposition it
Select(CursorPosition, 0);
}
}
PreviousLength = Text.Length;
}
}
答案 1 :(得分:0)
This控件支持过滤。它还会加粗您尝试过滤的字母。为了解决这个问题,在您的情况下,出现不良行为,我建议将“粗体”字体更改为与普通字体相同。