'TextChanged events from Textbox don't come in order

I am trying to dynamically filter data based on a number entered into a TextBox as the user types in characters. I am finding though that the text values seem to come out of order and I have no idea why. For example, if the textbox already has "1379" in it and I then type in "2019" after that (so finishing with "13792019"), I am getting the following:

    TxtFilter_TextChanged; text 13792; Time: 637865675822596714
    TxtFilter_TextChanged; text 1379201; Time: 637865675846017202
    TxtFilter_TextChanged; text 13792019; Time: 637865675847734984
    TxtFilter_TextChanged; text 137920; Time: 637865675849383373

I am logging the Time in Ticks. I can definitely see that the values are increasing, but I have no idea why/how "137920" is coming in after "13792019"? I can consistently reproduce this.

Right now, I cause the postback to happen on keyup so that I can set the focus back on the textbox. On OnFocus, I am setting the cursor to the last position (otherwise it goes back to the start). I'm open to better ways of doing this...

<script type="text/javascript">
function RefreshUpdatePanel(e) {
    __doPostBack('<%= txtFilter.ClientID %>', '');
    document.all.txtFilter.focus();
};

function SetEnd(txt) {
    if (txt.createTextRange) {
        //IE  
        var FieldRange = txt.createTextRange();
        FieldRange.moveStart('character', txt.value.length);
        FieldRange.collapse();
        FieldRange.select();
    }
    else {
        //Firefox and Opera  
        txt.focus();
        var length = txt.value.length;
        txt.setSelectionRange(length, length);
    }
}

Codebehind: The LoadOrderList method binds the data based on the filtered text, and then loads the order info for the first item selected, if any.

protected void Page_Load(object sender, EventArgs e)
{
    if (!Page.IsPostBack)
    {
        txtFilter.Attributes.Add("OnFocus", "SetEnd(this);");
        txtFilter.Attributes.Add("OnKeyUp", "RefreshUpdatePanel();");

        LoadOrderList();
    }
}

protected void TxtFilter_TextChanged(object sender, EventArgs e)
{
    DateTime dtNow = DateTime.Now;
    System.Diagnostics.Trace.WriteLine(string.Format("TxtFilter_TextChanged; text {0}; Time: {1}", ((TextBox)sender).Text, dtNow.Ticks));
    LoadOrderList();
}


Solution 1:[1]

I would not do a full page post-back here. You need to do a web API call, pass the text box, get the response back. Do you have use of the ajaxtoolkit? It has a auto complete pre-built, and lets you set the timing/delay, and even number of characters you have to type.

Now, I might not want to adopt the whole ajaxtoolkit for this ONE feature, but I certainly would consider the tool kit - as the autocomplete does work well, and auto magic wires up the ajax calls for you - without a page post back.

And it easy to use.

You also get mult-select combo boxes, a really slick dialog box (easier then bootstratp, or jquery.ui ones to use). And you get to VERY nice up-loaders.

So, consider the ajaxtoolkit. It is certainly and somewhat dated, but if your project is still web forms, then I would consider adopting the tool kit, since then you can a working auto-complete example and tool - one that been battle hardened an one that you know just works well.

In fact, note ONE BIG ELEPHANT in the room here?

What is it?

Why of course no one was willing to post THEIR working example, and suggest/have show what they use for this VERY common task and feature.

And since no one is posting examples, then it VERY much means the time and effort to setup such and example is MORE TIME then what it takes to post on SO.

And if the time taken to show such an exmaple is MORE then what it takes to post on SO as simple answer?

You ALEADY FAILED!!! - in other words, you want this kind of feature not only now but what about the next 10 examples you want to do this again? and again???

So the REAL goal, the REAL answer?

Regardless of WHAT and WHICH road you take, you MOST CERTIANLY want to go down a road in which a working solution can be used over and over.

So, say I want to search for some hotel names. So, drop; in a text box, then click on the ajax tool kit extender.

So, I dropped in a text box, and then go:

enter image description here

Now, select auto complete

enter image description here

So, now my markup is this

    <font size="4">Search for Hotel : </font>
    <asp:TextBox ID="txtHotel" runat="server" Width="250px">
    </asp:TextBox>  

        <ajaxToolkit:AutoCompleteExtender
            ID="txtHotel_AutoCompleteExtender" runat="server" 
            BehaviorID="txtHotel_AutoCompleteExtender" DelimiterCharacters="" 
            ServiceMethod = "GetHotels"
            MinimumPrefixLength="1"
            TargetControlID="txtHotel">
        </ajaxToolkit:AutoCompleteExtender>

And the code behind? This:

    [WebMethod()]

    public static List<string> GetHotels(string prefixText, int count)
    {
        List<string> Hotels = new List<string>();
        using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.TEST4))                
        {
            string strSQL 
                = "SELECT HotelName FROM tblHotels " +
                   "WHERE HotelName like @SearchText + '%' " +
                   "ORDER BY HotelName";
            using (SqlCommand cmd = new SqlCommand(strSQL,conn))
            {
                cmd.Parameters.Add("@SearchText", SqlDbType.NVarChar).Value = prefixText;
                conn.Open();
                using (SqlDataReader sdr = cmd.ExecuteReader())
                {
                    while (sdr.Read())
                        Hotels.Add(sdr["HotelName"].ToString());
                }
            }
        }
        return Hotels;
    }

And now we have this:

enter image description here

And you get a whole property sheet - you can customize the dealy, prefix length - all the setting and setup is done for you.

so, you have these settings:

enter image description here

So, there "are" existing tools for this.

But I think MUCH MORE then just going out and picking any old tool?

The real deal, the real issue?

Do you have a tool that lets YOU SPEND THE TIME here on SO to answer a question, to show a working example???

The fact that no one else is willing to do this?

It does not mean they are mean people, bad people, or even lazy people.

But it DOES mean they not picked a solution that gives you wizards, helpers, and built in UI designers that ALLOWED me to do all this work - in near record time, since I used a VERY easy solution.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Albert D. Kallal