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"
Related
I'm currently trying to create a web based wizard tool. I have a Wizard page that contains navigation buttons and an asp panel that will contain the individual wizard panels.
<asp:Panel ID="wizardControlPanel" runat="server">
<!-- Wizard panel goes here -->
</asp:Panel>
<asp:Button ID="backButton" runat="server" Text="< Back" OnClick="BackButton_Click" />
<asp:Button ID="nextButton" runat="server" Text="Next >" OnClick="NextButton_Click" />
<asp:Button ID="cancelButton" runat="server" Text="Cancel" PostBackUrl="~/"/>
One control dynamically fills a checkboxlist
<asp:Label ID="Title" runat="server" Text=""></asp:Label>
<asp:Label ID="DescriptionLabel" runat="server" Text ="Description for the wizard"></asp:Label>
<asp:CheckBoxList ID="ProjectSelector" runat="server" DataTextField="ProjectName" DataValueField="Id" ></asp:CheckBoxList>
I dynamically load this control into my wizardControlPanel once the checkbox is populated.
WizardControl = (BaseWizardControl)LoadControl(("~/Views/" + e.ControlType.Name + ".ascx"));
wizardControlPanel.Controls.Add(WizardControl);
The problem is; on postback I then need to be able to find out which checkboxes were checked server side, but the control no longer exists.
I can't find it on the _page variable. Running in to problems (I think) because I am adding the control to a content holder. How can I get this control back?
It is there, you just won't be able to access it using an ID. You'll need to find it by looking through the wizardControlPanel.Controls collection. I think there is a property that represents the filename you used. But it would be best to use the debugger to track down either where it is in the collection or an identifier you can use to find it.
Having done this once or twice, I think I also remember that you'll need to recreate the control prior to the OnLoad event of the life cycle so that the postback will be able to populate it.
As Markus says, there is probably a better way to do what you are trying to do. But if you MUST load this dynamically, this is how you should go about locating it.
If you add controls dynamically in ASP.NET WebForms, you need to re-add them manually very early in the page lifecycle of the PostBack (e.g. by overriding OnInit and creating the control with the same id in this code) in order to be able to retrieve the values. See this link for a How-To.
The following sample shows the basic steps. It consists of an ASPX-page that contains a Panel as a placeholder:
<asp:Panel ID="wizardPanel" runat="server">
</asp:Panel>
<asp:Button ID="btn" runat="server" Text="Do a postback" />
<br />
<asp:Label ID="lbl" runat="server" />
This is the codebehind-file:
public partial class DynamicUserControls : System.Web.UI.Page
{
protected UserControl userCtrl;
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
if (Page.IsPostBack)
CreateUserControl();
}
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
CreateUserControl();
else
{
lbl.Text = "The following values were selected: " + string.Join(", ", ((IGetSelectedValues)userCtrl).SelectedValues);
}
}
private void CreateUserControl()
{
if (Request["UserCtrl"] == "A")
{
userCtrl = (UserControl) LoadControl("~/MyUserControlA.ascx");
userCtrl.ID = "myUserCtrl";
wizardPanel.Controls.Add(userCtrl);
}
else if (Request["UserCtrl"] == "B")
{
userCtrl = (UserControl)LoadControl("~/MyUserControlB.ascx");
userCtrl.ID = "myUserCtrl";
wizardPanel.Controls.Add(userCtrl);
}
}
}
The basic steps are the following:
The page determines the user control type to be created upon a Request parameter during Page_Load (or later if necessary). It assigns the ID myUserCtrl to the UserControl.
Upon a PostBack, the page inspects the Request parameters again and re-creates the UserControl with the same ID myUserCtrl. This is important so that ASP.NET can retrieve the new values of the control from the postback data after the page initialization phase. The hardest part is usually to decide which user controls to create, because the data that are available in OnInit is usually not too many.
In Page_Load, the user control can be accessed and the values that were posted back are available. The UserControls in the sample contain a CheckBoxList and implement an interface that allows to retrieve the values that were selected by the user.
In most cases it is easier to find a different approach. Maybe you can use a MultiView control for your wizard that contains the UserControls for the wizard pages as static content. See this link for a description of how to use the MultiView control. If there are not too many (read unlimited) different UserControls to use, this approach is much more stable.
I was looking in the wrong place. Page.Form as opposed to Page.Request.Form. Due to the fact the checkboxlist is already defined in the user control, it's name is traceable in this variable. This way I can keep the current wizard structure.
this is my scenario:
I want to display a button(btnGenerate) based on the amount of rows displayed in my gridview. I've gotten it to display for a second then it goes away again. I'm using the onclientclick of one of my other buttons(btnImport). What I think is causing the problem is that on the same button(btnImport)'s OnClick event two gridview's performs for each a databind. Could this be the problem? I have written a script using javascript to perform this task from the client side. Is there a better way to do it? What can I do to fix my problem?
Here is my code that I have so far:
<asp:Button runat="server" ID="btnImport" Text="Load Data from File"
BackColor="#990000" ForeColor="White" nowrap OnClick="btnImport_Click"
style="display:none" OnClientClick="DisplayButtonGenerate()"/>
<asp:Button ID="btnGenerate" runat="server" Text="Generate New Stock Codes"
BackColor="#990000" ForeColor="White" OnClick="btnGenerate_Click"
style="display:none" />
I have two gridviews : ErrorsGrid that displays all the faulty records and InventoryGrid that displays the records that are correct. Like I said above, the idea is to display btnGenerate if ErrorsGrid has rowCount=0.
protected void btnImport_Click(object sender, EventArgs e)
{
InventoryGrid.DataBind();
ErrorsGrid.DataBind();
}
protected void btnGenerate_Click(object sender, EventArgs e)
{
FinalMessage.AppendLine(_InsertWrapper.PostData());
}
Here is the script:
<script language="javascript" type="text/javascript">
function DisplayButtonGenerate() {
var rowCount = <%=ErrorsGrid.Rows.Count %>;
var buttonGen = document.getElementById("<%=btnGenerate.ClientID%>");
if(rowCount == 0)
{
buttonGen.style.display = "block";
}
}
</script>
Your btnImport has server-side OnClient and client-side OnClientClick both set. I guess what's happening is the client-side is called first, shows the button, then the server-side one kicks in, the page gets refreshed from the server, and your button is hidden again. You can do it in one way or another, but not both:
Server-side: Remove the OnClientClick & style="display:none" & JavaScript, set the Visible property of the button to false, and in the code-behind click event on the server add:
if(ErrorsGrid.Rows.Count == 0)
btnImport.Visible = True;
Client-side: Return false from the JavaScript function to the OnClientClick:
OnClientClick="return DisplayButtonGenerate()"
function DisplayButtonGenerate() {
....
return false;
}
If you want to update InventoryGrid,ErrorsGrid grid controls in code after you click a button, you need to keep those in a UpdatePanel
<asp:UpdatePanel ID="upnl" runat="server" UpdateMode="Conditional">
<contenttemplate>
InventoryGrid,ErrorsGrid mark up
</contentTemplate>
<Triggers>
//set async trigger as btnImport
</Triggers>
</asp:UpdatePanel>
Let's breakdown your problem into steps.
you click on btnImport, it first calls the OnClientClick, does client side processing
and then does a full postback, goes to server side and processes its server side handler OnClick.
after the OnClick handler is processed, the page again renders, the unconditioned code in the btnGenerate display:none again runs, and the default state is again rendered.
you see the problem? even if you are manipulating certain logic in your clientClick, it all resets on page reload, because your btnImport is doing that.
Solutions:
there are couple of things I can suggest.
Use UpdatePanel to prevent Postback of the entire page or
make your btnImport a client side button altogether, and do a post using xhr or jQuery's ajax.
Set the visibility of btnGenerate on the server side itself
most simple would be the 3rd one i.e. remove the onclientclick event from the code and change your btnImport to do this:
protected void btnImport_Click(object sender, EventArgs e)
{
InventoryGrid.DataBind();
ErrorsGrid.DataBind();
//set visibility of btnGenerate in Page_Load also;
btnGenerate.Visible = ErrorsGrid.Rows.Count == 0;
}
and remove display:none from btnGenerate from client
There's no need for a JS function here.
Simply check the datasource for ErrorsGrid if count != 0 and if it's not just set the visibility of your button in codebehind.
If i've understood your req. correctly, setting 'Visbible' property of button to true or false should work. i.e btnGenerate.Visible=true/false. Initially you can set the button visibility as false then based on the record count you can modify it in the required event handler.
This question already has answers here:
How to fire Textbox textchanged event while typing in textbox
(3 answers)
Closed 9 years ago.
In my project i am using Textbox inside updatepanel to display the Receipt number which is not already exist in db table.
But the textchanged event on the textbox is not firing while typing. My Logic is to display available receipt while typing. If nothing displayed then user can insert that receipt number.
<asp:UpdatePanel ID="updAvailableReceipt" runat="server">
<ContentTemplate>
<asp:TextBox ID="txtReceiptNo" runat="server" class="textBoxStyle" AutoPostBack="true" OnTextChanged="txtReceiptNo_TextChanged"></asp:TextBox>
<asp:GridView ID="grdShowAvailableReceipt" runat="server" EnableTheming="True" ShowHeader="False"></asp:GridView>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="txtReceiptNo" EventName="TextChanged" />
</Triggers>
</asp:UpdatePanel>
protected void txtReceiptNo_TextChanged(object sender, EventArgs e)
{
param = ParameterClass.IniliazeParameter(1);
int count=0;
ParameterClass.AddParameter(ref param, "#ReceiptNumber", txtReceiptNo.Text, ref count);
grdShowAvailableReceipt.DataSource = new bAuctionPayment().Fetch(RecordFetchMode.FethcAvailableReceipt, param);
grdShowAvailableReceipt.DataBind();
}
This question is already exist but not answered yet...
Textchanged event will not get fired while you are typing. It will get fired when you lose focus so your code is fine just that you are expecting something which is never going happen. Try combining jquery ajax calls instead of updatepanel if you want a partial update of your page. Will try and give you an example here in some time.
Hope this helps (for the time being :))
P.S.: I am wondering why have you added asp.net mvc tag for this question.
EDIT:
The link here has an example which you can download. This example is pretty similar to what you are trying to achieve. Check it out.
Also just as Saurabh mentioned, you can use "keyup" event of the textbox in jquery to make the ajax call given in the link. The following is the code for the same.
$('#<%= TextBox1.ClientID %>').keyup(function () {
//Make ajax call here
alert('hi'); });
You can use the Ajax AutoCompleteExtender for that particular textbox.
<asp:TextBox ID="textbox1" runat="server" AutoPostBack="true"></asp:TextBox>
<asp:AutoCompleteExtender ID="textbox1_AutoCompleteExtender" runat="server" CompletionInterval="1"
CompletionSetCount="10" DelimiterCharacters="" Enabled="True" MinimumPrefixLength="1"
ServiceMethod="CreateAWebServiceMethod"
ServicePath="FilePathWhichContainsTheWebServiceMethod" TargetControlID="textbox1" UseContextKey="True">
</asp:AutoCompleteExtender>
Service method is your WebServiceMethod which you want to fire when you start typing in the textbox1.
Service path is the path of the file which contains your web service method.
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.
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
}