Fanto
Fanto

Reputation: 137

c# keydown code not working

I have a TextBox used to make research by keyword. I have checkboxes to filter the results and also a graph to display occurences of keyword in the table. The search is done once you click on the button made for it, it also works if I click on Enter Key. The problem is that if I decide to check 2 checkboxes and Click on Enter, the research is not made, or if I change the keyword and click again on Enter the result of the graph is not made. I'd like it to work whenever I click on the button or Enter.

I'm using KeyDown like I saw on the internet but it's not changing anythhing, no error either.

My code :

        protected void btnSearch_Click(object sender, EventArgs e)
        {
            Populate();

        }

        protected void tbSearch_KeyDown(object sender, KeyEventArgs e) 
        {
            if (e.KeyCode == Keys.Enter)
                btnSearch_Click(null, null);
        }

Can someone help me ?

Upvotes: 1

Views: 426

Answers (2)

Michel Amorosa
Michel Amorosa

Reputation: 495

On your textbox, just

  • add the attribute autopostback="true"
  • add the attribute OnTextChanged="btnSearch_Click"

and it will do what you want without JQuery

--> autopostback: postback to server when an event is triggered

--> OnTextChanged: when you get out of textbox (or press enter), the event is triggered and go to your search function

Upvotes: 1

Fanto
Fanto

Reputation: 137

Ok I've found the problem, I didn't mention I was using update Panel. So here is the code working for me :

$('#tbSearch').keydown(function (e) {
    var key = e.which;
    if (key == 13)  // the enter key code
    {
        //your code
    }
});

To make that code work with updatePanel :

//On UpdatePanel Refresh.
var prm = Sys.WebForms.PageRequestManager.getInstance();
if (prm != null) {
    prm.add_endRequest(function (sender, e) {
        if (sender._postBackSettings.panelsToUpdate != null) {

            $('#tbSearch').keydown(function (e) {
                var key = e.which;
                if (key == 13)  // the enter key code
                {
                  // your code
                }
            });
         }
    });
};

Upvotes: 1

Related Questions