Click here to Skip to main content
15,892,059 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,

How to call a C# Method on KeyPress of the TextBox in Asp.net Application.

Please provide the one sample for the same
Posted
Comments
Richard C Bishop 18-Oct-13 12:13pm    
Well, you call the method inside the KeyPress event handler.
Ganesh_verma 18-Oct-13 12:16pm    
But there is no keypress event in Web application.
Richard C Bishop 18-Oct-13 12:18pm    
So use OnTextChanged. It is basically the same thing.
Show your progress. What have you tried?

In ASP.NET Page
ASP.NET
<asp:textbox id="MyTextBox" runat="server" onkeypress="__doPostBack(this.name,'OnKeyPress');" ></asp:textbox>


In CodeBehined file
C#
protected void Page_Load(object sender, EventArgs e){
    var ctrlName = Request.Params[Page.postEventSourceID];
    var args = Request.Params[Page.postEventArgumentID];

    if(ctrlName == MyTextBox.UniqueID && args == "OnKeyPress"){
        MyTextBox_OnKeyPress(ctrlName, args);
    }
}

private void MyTextBox_OnKeyPress(string ctrlName, string args){
    //your code goes here
}


Every time you press a key page get submitted which causes the page to be refreshed totally.
Use updated panels to avoid full page submissions.

Hope this will help you
 
Share this answer
 
v2
You can use Javascript.
C#
OnPageLoad()
 {
  TextboxId.Attributes.Add("onclick") = "myfunction(this.Id)";
 }


Javascript on aspx file:
JavaScript
myfunction(textboxid){
//do your stuff
}
 
Share this answer
 
v2
Yes it is correct in asp.net server side control text box has no any keypress event. OnTextChange is there the code smample like
Server side code

C#
protected  void My_OnTextChanged(object sender, EventArgs e)
       {
           var txt = sender as TextBox;
           string value = txt.Text;
       }


In markup declaration


<asp:textbox id="txtOne" runat="server" ontextchanged="My_OnTextChanged" autopostback="true" xmlns:asp="#unknown">


Just remember that AutoPostBack property is very important there without that the textbox control will not be postback. Another is when you finish to write your data to the textbox after that when you press enter or tab that time the event is triggered. It is similar to lost focus event of windows application.
If you really want to go actual keypress event then you must go dom key press event and use javasript/jquery for subscribe that event.

//DOM ready event
$(function(){
//subscibe keypress event
$("[id$='txtOne']").bind('keypress', function(event){
//your key handling code is there
});
}).
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900