love Computer science
love Computer science

Reputation: 1828

how do I handle KeyPress or KeyDown events in asp.net?

KeyPress or KeyDown events aren't available in System.Web.UI.WebControls.TextBox so one way to do it is using Java-Scripts, but want to fire some Sql queries at these events. is it possible to execute Sql queries from JavaScript? if not then how do I do it?

Upvotes: 0

Views: 8181

Answers (3)

Bibhu
Bibhu

Reputation: 4081

You can handle the key press event in the given way

But you can't fire SQL queries in these events.

<%@ Page Language="C#" %>
<script runat="server">

protected void Page_Load(object sender, EventArgs e)
{
   if (!Page.IsPostBack)
   {
      Label1.Text = "Start";
   }
   TextBox1.Attributes.Add("onkeyup", "rewriteLabel()");
}
</script>

<script type="text/javascript">

function rewriteLabel()
{
   TextBox1.Text = Label1.text;
}

</script>

<html xmlns="http://www.w3.org/1999/xhtml" >
<head >
   <title >test</title>
</head>
<body>
   <form id="form1" runat="server">
      <br />
      <asp:TextBox ID="TextBox1" runat="server" /><br />
      <asp:Label ID="Label1" Runat="server" BorderWidth="1px" />
   </form>
</body>
</html>

Upvotes: -3

Chris Cap
Chris Cap

Reputation: 1068

No, You cannot execute SQL from javascript. Your best bet is to use something like jquery and wire up an event to .change() (or something simiiar) and then make an ajax request to perform the sql query. A server side event (which doesn't exist) for textbox key press or key down would submit the page everytime and that just wouldn't work for the user. You might look into jquery ui autocomplete if you're looking to display some information

Upvotes: 5

Jamie Dixon
Jamie Dixon

Reputation: 54001

If you need to capture key events, you'll need to use Javascript.

You can use ajax to then send these keys to the server and perform actions.

My guess is that you're thinking of something along the lines of Google Suggest.

Upvotes: 2

Related Questions