How to add event when press enter using C#? - c#

I have solution when add text in textbox and press Enter the
textbox content inserted in DB , I tried to get the best solution for
that but I couldn't . so How can I add event when press Enter?.
<asp:TextBox runat="server" id="txt_home">Add Comment</asp:TextBox>

in asp.net the simplest way is to use a Panel that warps the textboxes, and what ever user fills, and set DefaultButton to the action you wont when the user press Enter for the included text boxes.
<asp:Panel runat="server" ID="pnlAct" DefaultButton="Button1">
<asp:TextBox runat="server" id="txt_home">Add Comment</asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="Button" />
</asp:Panel>
Of course you can use custom javascript to capture the Enter and make custom post back, but asp.net all ready gives you a safe and "ready to use solution".

The most usual event in a textbox is the TextChangedEvent. I suppose this is what you are looking for. The link provided, gives you also this example:
protected void TextBox1_TextChanged(object sender, EventArgs e)
{
Label1.Text = Server.HtmlEncode(TextBox1.Text);
}
Alternatively, you could use javascript to capture a keydown or a keyup event. Then you could check if the key pressed is the Enter key. For example:
$(".input1").keyup(function (e) {
if (e.keyCode == 13) {
// Do something
}
});
Hope I helped!

Related

All control are fired in asp.net

since I am new to ASP .NET I wonder whether this is normal behavior or something strange. I am trying to convert C# WinForms app to web app and it is behaving not as I expected.
In desktop app I get data after user press enter on textbox. Data are loaded I can modify it and then, when I am done changing data I can press one of two buttons and data are saved to database or form is cleared. Something like this.
private int idOrder;
protected void TextBox1_TextChanged(object sender, EventArgs e)
{
if(load_data)
{
label1.Text = "some loaded data";
...
else{ MessageBox.Show("Something went wrong. No data loaded");
}
}
protected void Button2_Click(object sender, EventArgs e)
{
//save to database;
}
But When I try to do the same in ASP.NET Web form, whenever I press enter on textbox all controls are fired (as it is written in source code line after line) when page is refreshed. Could you please advice we what should I do to replicate same behavior as in winforms e.g. user input - enter - load data - modify - press button when I want. Thank you.
//Is the view state thing I am looking for?
Here is a snippet to get you started. Keep in mind that posting a HTML form when pressing enter is default behavior for websites. So the first thing is preventing that by wrapping the TextBox and Submit Button with a Panel with a DefaultButton assigned to it. Now when the enter is pressed in TextBox1, it will post the form as dummyButton
Next we add an OnTextChanged event to TextBox1 and set AutoPostBack to true. This will fire when the focus of TextBox1 is lost. You could remove this and just use the enter with dummyButton.
The dummyButton is added to ensure the form will PostBack when enter is pressed in TextBox1 to get the desired behaviour.
<asp:Panel ID="Panel1" runat="server" DefaultButton="Button1">
<asp:TextBox ID="TextBox1" runat="server" AutoPostBack="true" OnTextChanged="TextBox1_TextChanged"></asp:TextBox>
<br />
<br />
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
<br />
<br />
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
<asp:LinkButton ID="dummyButton" runat="server" OnClick="TextBox1_TextChanged"></asp:LinkButton>
</asp:Panel>
And then in code behind.
protected void TextBox1_TextChanged(object sender, EventArgs e)
{
//load from database
Label1.Text = TextBox1.Text;
}
protected void Button1_Click(object sender, EventArgs e)
{
//save to database
Label1.Text = "Data saved!";
TextBox1.Text = "";
}
You can also prevent PostBack with enter like this. The JavaScript will block all enters. Depending on your page design you could set this in the <body> tag for example.
<div onkeydown="return (event.keyCode!=13);">
<asp:TextBox ID="TextBox1" runat="server" AutoPostBack="true" OnTextChanged="TextBox1_TextChanged"></asp:TextBox>
</div>

Reset session upon textbox input change in asp .net c#

I have session in a page and would like to reset this session when the user text input changes. For example: account number xxx will have a session, once account number changes to yyy i would like to reset session. I dont have login to this page so cannot dump session upon logout. help is appreciated. thank you in advance.
Try this:
in aspx:
<asp:TextBox ID="TextBox1" runat="server" ontextchanged="TextBox1_TextChanged"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="Button" />
in code behind:
protected void TextBox1_TextChanged(object sender, EventArgs e)
{
Session.Clear();
}
So you'll need an event handler that is fired when the account number changes (or whenever the user text input changes), and then according to this post you'll need to either use Session.Clear() which just removes all values from the object or Session.Abondon() which will destroy the session and trigger the Session_OnEnd event. Whichever you use will depend on what you want to accomplish.
make ajax call on "onkeyup" event of textbox and set new value in that session, you will get new value of textbox and can set it in session.
Use TextChanged event of TextBox and destroy the session using Session.Abandon() or Session.Clear() method
This will help you
If you write down code here, then we can give you exact answer
try this
<asp:TextBox ID="TextBox1" runat="server" ontextchanged="TextBox1_TextChanged"></asp:TextBox>
code behind
protected void TextBox1_TextChanged(object sender, EventArgs e)
{
Session["your_sesion_name"]=TextBox1.Text;//or what ever you want to update value
}
There are a couple of ways to do what you are asking.
Option one:
You could uses the text boxes ontextchanged event
<asp:TextBox ID="TextBox1" runat="server" ontextchanged="TextBox1_TextChanged" AutoPostBack="true"></asp:TextBox>
in code behind:
protected void TextBox1_TextChanged(object sender, EventArgs e)
{
Session.Clear();
}
The pit fall here is the OnTextChanged event is only fired once the textbox has lost focus.
Option 2:
Uses JavaScript to capture the onkeyup event and make an ajax call back to the server to update your session information
The pit fall here is that every time the user enters a character into the textbox you would be making the ajax call. Although you could add checks so that the call is only made if the account number is a certain length.
Option 3:
You could add a button to your form for the user to click once they have entered the account number. This would avoid needless calling the server on every key press as in option 2. Then within you buttons click event you could do the work with your session
<asp:TextBox ID="TextBox1" runat="server" />
<asp:Button ID="btnSubmit" runat="server" onclick="btnSubmit_Click" Text="Submit" />
Code behind
protected void btnSubmit_Click(object sender, EventArgs e)
{
// do session work
}

Stop Enter key from firing button click event

I am hoping this is easy, but I have looked and can't find a solution that will work for me. I have an aspx page with 2 user controls on it. One is a user control with a spun-up Auto Complete text box, that I want the "Enter" key to to cause a postback.
I have a button in the other control on the page that the onClick does something else. When I put text in the Auto Complete and press enter, the onClick for the button fires. Is there a way to have the enter key not cause the onClick to fire.
I have tried some javascript to disable the enter key press, but that breaks my text box enter.
What are my options.
EDIT 1
Here is some markup that I have
<uc:CompanyAC runat="server" ID="ac" />
<cc2:GenericGridView OnHtmlDataCellPrepared="HtmlDataCellPrepared"
KeyFieldName="CompanyID" ID="gridCompanies" DataSourceID="ManageCompaniesObjectDataSource" runat="server"
AutoGenerateColumns="False" />
The CompanyAC control has a textbox with some jquery that does autocomplete WS call (no need to show that
<asp:TextBox ID="searchbox" runat="server" Width="400px" />
The GenericGridView control contains a button
<asp:Button runat="server" ID="Button" Text="New" AllowFocus="false" OnClick="Button_Click" />
So what happens is that when the Enter Key is hit when the focus is on the Textbox, the button that is in the other control fires its onclick. I do not want that to happen, but I still want the postback to happen
try this
$('input').keypress(function(event){
if(event.keyCode==13)
{
event.preventDefault();
}
})
If you're using jQuery, you might try this:
$('input').on('keypress', function(e){
// Attempt form submit (after event function exits).
var f = $(this).parents('form');
setTimeout(function(){f.submit();}, 1);
// Return false to prevent form submit when enter key is pressed.
return !((window.event) ? window.event.keyCode : e.which)==13);
});

How to check if enterkey is pressed in a TextBox in asp.net

I have a asp.net Text Box which accepts date in the format MM/DD/YYYY. After entering the date i will hit enter key.if enter key i need to execute server side code.How can we achieve this ?
The problem with Text box is it will fire the Text Changed event only if it looses the focus.
You can use the Panel.DefaultButton property to automatically click a button when the user presses Enter.
For example:
<asp:Panel Id="panel1" runat="server" DefaultButton="btnSubmit">
<asp:TextBox Id="txtDate" runat="server" />
<asp:Button Id="btnSubmit" Text="Submit" OnClick="btnSubmit_Click" runat="server" />
</asp:Panel>
If you don't want to show the button, you can set its style="display: none".
you set jquery tag
so using jquery u can try something like this
$("#field").keydown(function(e){
if(e.keyCode === 13)
{
// enter event
}
});
Use the keydown event:
textBox.Attributes.Add("onKeyDown", "KeyDownHandler()");
Have KeyDownHandler() check the pressed key and if correct, submit the surrounding form or invoke an AJAX request. See keyboard codes at Javascript Char Codes.
Alternatively, textbox ID can be injected into jQuery from .aspx and assigned a direct keydown handler:
$('#<%=textBox.clientID%>').keydown(function (e) { /* Do server request; */ });
You can call this Javascript function to check whether enter key has been pressed or not.
function checkEnterKeyPress(e)
{
var key;
if(window.event)
key = window.event.keyCode; //IE
else
key = e.which; //firefox
if (key == 13){
alert(key);
}
}

5 Textbox, 2 Buttons. How to assign textBox to Button?

I want to give my users the option to use a textbox and press Enter. The challenge is that I have 5 textbox, and 2 options. 3 textbox belong to one button, and 2 textbox to the other. How do I trigger a particular Button according to the textbox the user was in when he press Enter?
I accomplished this on my own where I had a page with two different login forms for the different user types. What I did was separate the two forms into their own ASP Panel controls and on the panel setting the DefaultButton to whichever one I wished. That way when they finished typing in the form and hit the enter key, it would submit on the correct button.
Example:
<asp:Panel id="panel1" DefaultButton="button1">
<asp:textbox id="textbox1"/>
<asp:textbox id="textbox2"/>
<asp:buton id="button1"/>
</asp:panel>
<asp:panel id="panel2" DefaultButton="button2">
<asp:textbox id="textbox3"/>
<asp:textbox id="textbox4"/>
<asp:button id="button2"/>
</asp:panel>
EDIT: Here is another method of how to do it by assigning an OnKeyPress property to your textboxes. THIS IS A SEPARATE SOLUTION THAN THAT WHICH I DESCRIBED AT THE TOP
Example:
function clickButton(e, buttonid){
var evt = e ? e : window.event;
var bt = document.getElementById(buttonid);
if (bt){
if (evt.keyCode == 13){
bt.click();
return false;
}
}
}
//code behind
TextBox1.Attributes.Add("onkeypress",
"return clickButton(event,'" + Button1.ClientID + "')");
The code behind generates the following code:
<input name="TextBox1" type="text" id="TextBox1" onkeypress="return
clickButton(event,'Button1')" />
In this situation I would group the related textboxes and the button in a Panel. Panel has a DefaultButton property you can use. DefaultButton="IdOfTheDefaultButtonForControlsInThisPanel"
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.panel.defaultbutton.aspx
Using jQuery this is fairly easy to accomplish:
$(function ()
{
$("#id-of-textbox-1, #id-of-textbox2, etc.").keyup(function (e)
{
if (e.keyCode === 13) $("#id-of-submit-button-1").click();
});
// And for the second group
$("#id-of-textbox-3, #id-of-textbox4, etc.").keyup(function (e)
{
if (e.keyCode === 13) $("#id-of-submit-button-2").click();
});
});
If you are using ASP.NET Button controls, be sure to set the property UseSubmitBehavior on those to false.

Categories

Resources