Reset session upon textbox input change in asp .net c# - 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
}

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>

Website doesn't see newest session values until I refresh page, but refreshing resets values of controls

My ASP.NET website doesn't see newest Session values. When my form is being sent to the server after clicking the button, the result sent back to browser depends of Session values. I process them in Page_Load method. It doesn't see the last change od Session values, but one before last. It looks like button's event handlers are executed before page's event handles but I'm not sure if it is like that.
I tried to do my code in other methods like Page_PreInit etc, but it's still the same like that. The only thing that works for me is refreshing the page: Response.Redirect(Request.Url.AbsoluteUri); after any change of any Session value, but it resets values of all controls, which I want to be the same as before. Is there a better solution?
Example: when It runs first time, the label's text is "Click the button", but when I click any of the buttons one time, nothing happens. When I click any of the button second time, label's text is the value of first click (even if I click A and then B, value changes to A after clicking B).
form:
<form id="form1" runat="server">
<div>
<p>
<asp:Label ID="Label1" runat="server" />
</p>
<p>
<asp:Button ID="Button1" runat="server" Text="A" onclick="Button1_Click" />
<asp:Button ID="Button2" runat="server" Text="B" onclick="Button2_Click" />
</p>
<p>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
</p>
</div>
</form>
Event handlers:
protected void Page_Load(object sender, EventArgs e)
{
Label1.Text = Session["Letter"].ToString();
}
protected void Button1_Click(object sender, EventArgs e)
{
Session["Letter"] = "A";
}
protected void Button2_Click(object sender, EventArgs e)
{
Session["Letter"] = "B";
}
Global method:
void Session_Start(object sender, EventArgs e)
{
Session["Letter"] = "Click the button";
}
Without your code its very difficult, but is sounds like you are setting a Session collection value in the code of a button's click event( or some other control/event ), and expecting it to be in the SESSION collection during the Page_Load event.
It doesn't work like that - When the page request comes in, Page_Load happens before the control's events.
Instead of Page_Load use Page_PreRender this event occurs before the page is prepared to be sent back to the client.
Your addition of the code confirms the above.
Normally I wouldn't use Session_Start to initialize stuff like this, use Page_Load and IsPostBack property
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack){
Label1.Text = "Click the button";
}
}

How can I identify, in an ASP.NET Page_Load event, what RadButton initiated a postback?

In my ASP.NET page's Page_Load I'm trying to determine whether a certain button has been clicked and is attempting a postback:
if (Page.IsPostBack)
{
if (Request.Params.Get("__EVENTARGUMENT") == "doStuff")
doSomething();
}
doStuff is a JavaScript within the markup, but I don't want this alone to trigger the doSomething() method call, I also need to be able to ensure that the button the user has clicked is correct.
How can I identify and reference the button control from the code behind once the user clicks? I searched for and discovered this but when I try to implement it, the control returned is always null.
Or use the CommandName and command events.
<telerik:RadButton ID="RadButton1" runat="server" CommandName="first" CommandArgument="one" OnCommand="CommandHandler" />
<telerik:RadButton ID="RadButton2" runat="server" CommandName="second" CommandArgument="two" OnCommand="CommandHandler" />
<asp:Label ID="Label1" Text="" runat="server" />
<asp:Label ID="Label2" Text="" runat="server" />
protected void CommandHandler(object sender, CommandEventArgs e)
{
Label1.Text = e.CommandArgument.ToString();
Label2.Text = e.CommandName;
}
You haven't really explained what you're trying to do, but it sounds like you would have a much easier time if you added an OnClick event handler to the button instead of trying to figure it out in Page_Load. The event handler would only be executed when that button is clicked.

How to add event when press enter using 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!

Lost Focus method for asp.net textbox?

How to write Lost focus method for asp.net text method? Please anybody have any idea to write this, share with me?
So I know everyone has shown the basic client side approach, and that is fine, but I wanted to at least show a solution for handling a specific client side event on the server.
Lets take a look at the code, and go over it piece by piece.
Since ASP.Net TextBox does not expose a server side event for OnBlur, you will have to do it manually. Fortunately this is pretty easy to achieve. Suppose you have this small bit of code in your .aspx page. You want to update a Label control server side whenever the TextBox loses focus.
<asp:Label ID="lblOnBlur" runat="server">On Blur Example</asp:Label><br />
<asp:TextBox ID="tbOnBlur" runat="server" ClientIDMode="Static" /><br />
<asp:Label ID="lblOutput" runat="server" />
ASP.Net has a built in client side function that gets called to trigger postbacks that takes two parameters:
Target (the ID of the control causing the event)
Argument (optional information you would like to pass to the server)
You could just wireup the event in markup by adding the following attribute and value to your TextBox:
onblur="__doPostBack('tbOnBlur','OnBlur');"
However, the framework has an easy way to generate this script for you server side. In your Page_Init method, simply add a call to GetPostBackEventReference and assign it to the "onblur" attribute for you control like so:
protected void Page_Init(object sender, EventArgs e)
{
var onBlurScript = Page.ClientScript.GetPostBackEventReference(tbOnBlur, "OnBlur");
tbOnBlur.Attributes.Add("onblur", onBlurScript);
}
With standard server control events, the event wireup and invocation is handled automagically for you by implementing IPostBackEventHandler. That is a lot of work for a one-off solution, so lets just handle it manually by inspecting the request params.
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
var ctrlName = Request.Params[Page.postEventSourceID];
var args = Request.Params[Page.postEventArgumentID];
HandleCustomPostbackEvent(ctrlName, args);
}
}
private void HandleCustomPostbackEvent(string ctrlName, string args)
{
//Since this will get called for every postback, we only
// want to handle a specific combination of control
// and argument.
if (ctrlName == tbOnBlur.UniqueID && args == "OnBlur")
{
lblOutput.Text = "On Blur Event Handled Server Side!" + DateTime.Now;
}
}
In the end it isn't terribly difficult to simulate server side events if you don't mind digging into the framework a little.
Hope this helps!
Cheers,
Josh
If you want the server to do something after the textbox loses focus you can add AutoPostback="True" and, if you don't want the postback to reload the whole page, use an UpdatePanel:
<asp:ScriptManager ID="ScriptManager1" runat="server" />
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:TextBox ID="TextBox1" runat="server" AutoPostBack="true"
OnTextChanged="TextBox1_TextChanged" />
</ContentTemplate>
</asp:UpdatePanel>
The function TextBox1_TextChanged can then do something with the text (serverside).
if (!Page.IsPostBack)
{
txtName.Attributes.Add("onblur","alert('Hello world')");
}
Why don't you use that. Lostfocus works same with:
OnTextChanged="TextBox_TextChanged"

Categories

Resources