?
Solved

calling a function inside a textbox control from a kepress event?

Posted on 2004-10-19
16
Medium Priority
?
800 Views
Last Modified: 2008-02-01
HI There,

I have a webform and I am wanting to call a function from a textbox control located on the webform when a key is pressed. Can this be done and if so, does anyone have an code to get me started?

Sean
0
Comment
Question by:bullrout
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 6
  • 5
  • 2
  • +3
16 Comments
 
LVL 10

Expert Comment

by:jnhorst
ID: 12355268
Yes:

In your Page_Load event, if the page is NOT a postback, do this:

txtTextBox.Attributes.Add("onkeypress", "javascript:yourFunction();");

If your function validates the key pressed and cancels the event if the keyCode is not a valid keyCode in your function, you might want to use the "onkeydown" event instead.

John
0
 
LVL 26

Assisted Solution

by:Rejojohny
Rejojohny earned 800 total points
ID: 12355273
do u mean a client-side script on key press .. if s, then do this ..
assuming ur textbox is called textbox1

on ur ASPX page .. write this code within javascript tags
<script laguage=javascript>
function trapKeypress() {
 alert (window.event.keyCode);
}
</script>

and in ur .vb page of the .aspx page .. add this line in the load event of the page
textbox1.attributes.item("onkeypress") = "javascript:trapKeypress();"
0
 
LVL 5

Author Comment

by:bullrout
ID: 12356185
Hi There,

is it possible to call a vb.net function from something like this?
0
VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

 
LVL 26

Expert Comment

by:Rejojohny
ID: 12356245
no ... this is not to call any vb.net function .. i hope u meant vb.net as code-behind ...

this is call client-side scripts to be called by the browser .. so u want to trap keypress on the server?? why would u want to do it .. I hope u understand the omplexity behind such a functionality .. on every keypress, the form has to be submitted .. or atleast use some remotescripting to make calls to code-behind functions .. also there is no keypress server side event handler .. u will have to use the "onchange" event  .. still i wouldn't advise that .. if u could explain what u r trying to do, i might be able to suggest an alternative solution ...
0
 
LVL 5

Author Comment

by:bullrout
ID: 12356283
Hi Rejojohny,

I did mean I want to call a function inside the code behind. What I want to do is to have a textbox and then when a user types a character the textbox is populated with the first entry inside the db of what they typed. For example if the user types "a" then the textbox would be populated with the first entry inside the table that began with "a".

I did toss up some different methods, populating a listbox with all of the entries and then selecting from this when the key is pressed.

Do you have any ideas?
0
 
LVL 26

Expert Comment

by:Rejojohny
ID: 12356317
normally I would use a dropdownlist for a similar scenario ... fill the dropdownlist with all the values from the database and dropdownlist has the functionality u have mentioned ... i.e. defauting to the first value found in the list.

if that doesn't suit ur needs . then based on ur requirement u will have to use the onchange event of textbox ... write ur code to populate the textbox from the databse in the onchange event (code-behind) of the textbox.But mind that this is not going too user friendly and excessive processing ...
0
 
LVL 5

Author Comment

by:bullrout
ID: 12356477
How do I call the non-javascript function from the event on the textbox control?
0
 
LVL 26

Expert Comment

by:Rejojohny
ID: 12356505
what do u mean by "non-javascript function" .. u mean code-behind? if s .. just double click on the textbox during design-time and it will open the code-behind (.vb page) .. write ur code there.. or u could also write code on ur .aspx page by specifying a script tag as runat=server .. like this

<script lanaguage=vb runat=server>

</script>

but i would not advise u to do this .. do it the other way as mentioned above ...
0
 
LVL 5

Author Comment

by:bullrout
ID: 12356559
Hi There,

I double clicked on the textbox and it produced the following code, (i added the label in) but to populate it I need to hit the enter key. How can I envoke this event with a keypress?

Private Sub TextBox1_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox1.TextChanged
        Label1.Text = "sean"
    End Sub
0
 
LVL 2

Expert Comment

by:raed_hasan
ID: 12356586
I also recommend to do the ways suggested above like Rejojohny  code, if u want to do something on server side You can submit the form in trapKeypress() ( as Rejojohny posted ). This will cause a postback and
you can pass to the server a sort of info telling what exactly caused the postback. This will resemble a server event.  You can't avoid using javascript on the client side.

 How can server know what is happening in the browser?
0
 
LVL 5

Author Comment

by:bullrout
ID: 12356674
ok I get what your saying, I was just hoping that another method was available to me.

Sean
0
 
LVL 44

Expert Comment

by:Arthur_Wood
ID: 12357071
trust me, what you THINK you want to do is a very bad idea.  It would be sort of like the following:

You and your 'significant other' go to a restaurant, for dinner.  The restaurant owner has decided that he wants to make sure that every partron gets the latest information about the availability of the choices on the menu, as they order, so after every word uttered by a patron, the waiter is to check with the kitchen to make sure that all of the choices on the menu that begin with the words spoken by the patron are still available.  That means that every time a patron says a word, the waiter must run into the kitchen, ask the chef if the items are still available, and run back to the table, to let the patron know that those items are still available, so that the patron can then add another word to the order, and the process is repeated.  Is that what you really want.  After every keypress, in order to execute a server-side function, the page must be submitted back to the server, the function executed, and the page returned back to the client.  That will make the page be VERY VERY slow.

AW
0
 
LVL 26

Expert Comment

by:Rejojohny
ID: 12357247
good example arthur :-) i have been trying to tell the same thing .. that the whole idea is bad. .. use a dropdownlist instead ... anyway thought "bullrout" might be trying some things out and might have some other genuine reason for designing such a form ..
0
 
LVL 18

Expert Comment

by:tusharashah
ID: 12357273
To enable this function,

Private Sub TextBox1_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox1.TextChanged
        Label1.Text = "sean"
    End Sub

---> You need to Set AutoPostBack=true in the Property of your TextBox.

This function will only be called once the focus will go out of TextBox & only if the Text inside that TextBox has been changed. & Page will be slow but not very very slow..(dont take it personally AW).. As, the page will post back only in the condition I stated above.!

-tushar
0
 
LVL 26

Expert Comment

by:Rejojohny
ID: 12357300
>>How can I envoke this event with a keypress?
autopostback of the textbox has to be set to true
0
 
LVL 10

Accepted Solution

by:
jnhorst earned 1200 total points
ID: 12361353
There is a way to do this client side with a textbox.  Get your data from the database into a data reader.  Iterate through the records in the data reader, appending each value to a comma delimited string.  Then write a <script></script> block to the browser in your Page_Load event that uses this comma delimited string to create an array (in JavaScript, this in the <script></script> block).  Then you could code a function for the onkeyup event of the textbox that would iterate through that array, and if it found a member that had the same first letter, it would populate the text box with that member.

Put this in your <head></head> section in the aspx page:

<script language="javascript">
// this is IE javascript.  Probably will not work right in other browsers.
function checkArray()
{
      // get keycode.
      var key = event.keyCode;
                  
      // test for certain keys.
      var test1 = (key == 37 || key == 39);            // 37 & 39 are left/right arrow keys.
      var test2 = (key == 46 || key == 9);            // 46 & 9 are delete and tab keys.
      var test3 = (key == 8  || key == 13);            // 8 is backspace. 13 is enter.
                  
      // ignore those keys in the tests.
      if (!test1 && !test2 && !test3)
      {
            for (i=0; i<arrList.length; i++)
            {
                  if (arrList[i].substring(0, 1).toLowerCase() == event.srcElement.value.toLowerCase())
                  {
                        event.srcElement.value = arrList[i];
                        break;
                  }
            }
      }
}
</script>

Then put this in Page_Load.

if (!this.IsPostBack)
{
                // I hard coded the string values here.  You would create this string by iterating through your data reader.
      string vals = "Abc,Bcd,Cde,Def,Efg,Fgh,Ghi,Hij,Ijk,Jkl";

                // you will register this block with the page to create the array that your checkArray() function will use.
      string js = "<script language=\"javascript\">\n";
      js += "var list = '" + vals + "';\n";
      js += "var arrList = list.split(\",\");\n";
      js += "</script>";

                // this causes the script defined above to be rendered to the browser.
      this.RegisterStartupScript("list", js);
               
                // this will add the onkeyup event to the textbox when it renders.
                this.txtBox.Attributes.Add("onkeyup", "javascript:checkArray();");
}

John
0

Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

I have developed many web applications with asp & asp.net and to add and use a dropdownlist was always a very simple task, but with the new asp.net, setting the value is a bit tricky and its not similar to the old traditional method. So in this a…
It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that unde…
This is my first video review of Microsoft Bookings, I will be doing a part two with a bit more information, but wanted to get this out to you folks.
Visualize your data even better in Access queries. Given a date and a value, this lesson shows how to compare that value with the previous value, calculate the difference, and display a circle if the value is the same, an up triangle if it increased…
Suggested Courses
Course of the Month11 days, 16 hours left to enroll

752 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question