Mr_Green
Mr_Green

Reputation: 41832

Enter key event for TextBox

I am new to asp.net. Here I am trying to create a chat application. In my project there is one label and one TextBox. whenever the user enters anything in TextBox and press enter the text will be shown in Label. I tried the below code:

OnEnterKeyPress of TextBox (.aspx.cs file)

        HttpRequest request = base.Request;           
        Ping p = new Ping();
        PingReply r;
        String s = request.UserHostAddress;  //using own IP address for understanding purpose.
        r = p.Send(s);
        Response.Buffer = false;
        if (r.Status == IPStatus.Success)
        {
            Label1.Text = TextBox1.Text;
        }

I dont know how to keep the enter event. (There are no events in TextBox properties as it were in C#)

Before asking here I checked many links like Link1 Link2 Link3 but no use. I could have used simple Javascript but the main code is in C# file.

Upvotes: 0

Views: 3397

Answers (3)

MikeSmithDev
MikeSmithDev

Reputation: 15797

You'll need to put this in its own form and use javascript, since it will be in a page with other controls. You don't want to "submit" the page every time they type something.

<form action="javascript:chat()">
put label and textbox here
</form>

This will make "enter" work for the textbox. For the chat feature, to make it more interactive, you can implement with http://signalr.net/

Upvotes: 1

keyboardP
keyboardP

Reputation: 69362

If there is only one button in the form that you want to enable 'enter' on, you can set it to be the default

protected void Page_Load(object sender, EventArgs e)
{
    this.Form.DefaultButton = myTextBox.UniqueID;
}

For any button, you will need to use Javascript. You can still use C# to add the attributes. (from here)

myTextBox.Attributes.Add("onkeydown", "if(event.which || event.keyCode)
                  {if ((event.which == 13) || (event.keyCode == 13)) 
                      {document.getElementById('"+Button1.UniqueID+"').click();
                                         return false;}} else {return true};");

Upvotes: 1

Christiaan Nieuwlaat
Christiaan Nieuwlaat

Reputation: 1359

The problem you might be facing here is the event will be processed server side ( after post ). You'll probably still need a javascript to do the post when the enter key has been pressed..

I'm also not certain if the OnEnterKeyPressed is a valid event.

Upvotes: 0

Related Questions