Reputation: 11
i am new in programing i need help regarding how to filter listbox via using textbox in c# application.
I mean enter some text into textbox and filter same time in listbox if items exits in lists then select into textbox else open new form for creating the items kindly give me example for the same.
Upvotes: 1
Views: 4949
Reputation: 4479
This control supports filtering. It will also bold the letters that you try to filter on. To get around that, in your case, undesired behavior, I suggest changing the 'bold' font to be the same as the normal font.
Upvotes: 0
Reputation: 17213
Here is a simple autocomplete textbox you should be able to use to fit your needs:
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;
}
}
Upvotes: 2