views:

464

answers:

1

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.

+1  A: 

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;
    }

}
Tommy
hi sniperxsee I don't have any idea about creating autocompleted textbox as per your suggested code i am confused that where is type this code in form1.cs or else where i am new here kindly guide me thx in advance
mahesh
You need to create a custom control. You dont "enter it into a file" you create a file. Add a file say, AutoCompleteTextBox.cs, compile your application, then look in the toolbox for your new controls. the code is ddocumented so the parts that need editing can be easliy edited.
Tommy