Daybreaker
Daybreaker

Reputation: 1047

Search while typing in textbox C#

I have two textboxes. One is to type CustomerId and other one is to display customer name.

What I want to do is: I want to get the search result to the CustomerName textbox while I am typing in CustomerId (get relevant customerName related to the CustomerId). This is not autocomplete. I want get the result without pressing enter in the textbox or pressing a button.

What is the best way to do this. I have used the textbox_textchanged event. Are there any other better way to do this? I am using Entity Framework.

Upvotes: 2

Views: 6378

Answers (2)

Selman Genç
Selman Genç

Reputation: 101721

You can use TextChanged event.Here is an example:

if(txtCustomerId.Text.Length > 0)
{
    int id;
    if(int.TryParse(txtCustomerId.Text, out id))
    {
       using (var ctx = new MyDbContext())
       {
            // get customer name by Id, for example:
           var name = ctx.Customers.Where(c => c.CustomerId == id)
                    .Select(c => c.CustomerName)
                    .FirstOrDefault();

           if (name != null) txtCustomerName.Text = name;
       }
    }
}

Upvotes: 3

Jesse Carter
Jesse Carter

Reputation: 21207

You can use the textbox_textchanged event however, one thing you're going to want to consider is that for this to work you're going to need to trigger database queries as the text values change. Doing this on every key press would be redundant so you're going to want to throttle the events somehow. (Reactive extensions offers some great functionality for that). After that you'll have to use the results from your Entity Framework query to populate your textbox. Without seeing any attempt at code from you its harder to give more specific recommendations but this is the way the functionality you're talking about is normally implemented.

Upvotes: 3

Related Questions