Focus on textbox inside gridview and updatepanel - asp.net

After breaking my head over something apparently simple, here I am:
I have an ASP.NET GridView wrapped inside an UpdatePanel. Once the user enters something in the last textbox of the last row and moves out, I add a new row to the gridview. This is done server-side by firing the OnTextChanged event of the textbox and setting its AutoPostBack property to true. This bit is Ajaxified by using the UpdatePanel.
My simple requirement is: I need to set the focus on the first textbox of the newly added row once the partial refresh is over.
What I tried:
//Get the newly added row (basically the last row)
GridViewRow newRow = myGridView.Rows[myGridView.Rows.Count - 1];
//Get the TextBox control on which I want to set focus
TextBox textBox = newRow.FindControl("txtMyCode") as TextBox;
//Set the focus
ScriptManager.GetCurrent(this.Page).SetFocus(textBox);
On stepping through the code, each of the above lines execute, and yet, when the partial postback completes, the textbox doesn't have the focus. The ScriptManager.GetCurrent(this.Page) returns an instance of the AjaxControlToolkitScriptManager, which is there on the Master page.
Any ideas?

You could write jquery to achieve this bit if you were not able to set focus from server site.
<script type="text/javascript">
Sys.WebForms.PageRequestManager.getInstance().add_pageLoaded(BindEvents);
function BindEvents() {
//write your logic here lets say
//if your grid view empty row is visible then set focus
}
</script>

You can use javascript pageLoad function which is Ajax-specific function fired every time the content of ajax update panel is refreshed. Inside that function trigger 'focus' on your text box.
function pageLoad() {
document.getElementById('ClientIdOfYourTextBox').focus(); }
You need to get ClientId of newly added text box in javascript. You can achieve it by saving it in hidden field server-side once it's added and then get hidden field's 'value' client-side or by building jquery expression (e.g. get last from all 'input' controls with id containing 'txtMyCode')

Related

checkbox not firing event after checked is set programmatically

I am iterating through a string of characters and finding a checkbox. I find the checkbox without any problems and if the character of the iteration is equal to 't', I set the Checked property of the checkbox to true.
However, for whatever reason, although it does check the appropriate checkboxes, executing this code also means that when I click any checkbox myself, nothing happens (everything works just fine and I can check anything until I execute this code). Also, the submit button on my page no longer does anything if I execute this code. I'm puzzled as to what may be the reason for this.
The buttons are created programmatically on init and are located inside an update panel.
DateTime date = new DateTime(2015, 11, 18);
foreach (char c in attendee.accommodation)
{
ID = "accommodationCheckBox" + date.ToShortDateString();
CheckBox checkbox = (CheckBox)FindControl(ID);
if (checkbox != null && c == 't')
{
checkbox.Checked = true;
}
date = date.AddDays(1);
}
Here is an example of how the checkbox looks like in the end: https://jsfiddle.net/Lzxo047o/
EDIT: Scenario: You fill in a dynamically generated form on A.aspx, then you see a "registration overview" on B.aspx. If you want to modify your registration at that point, you hit a button which creates a new instance of A.aspx and fills it with your registration data from database, which is what I'm solving right now. I dynamically create some checkboxes and based on a value of string, either check them or not. They get checked as they should, but I'm unable to manually control them / click them.
checkbox.CheckedChanged += yourcheck_event;
If the checkbox is created dynamically, you have to add the event to it.
Make sure your UpdatePanel has it's UpdateMode property set to "Always".
Take on count that:
the UpdatePanel control’s content is only updated when one of the
following is true:
When the postback is caused by a trigger for that UpdatePanel control.
When you explicitly call the UpdatePanel control's Update method. When
the UpdatePanel control is nested inside another UpdatePanel control
and the parent panel is updated.
…

ASP.NET: Find which element had focus before postback?

I have a series of controls on a page, including some textboxes that serve to record employee timesheet. When OnTextChanged fires, the page postback and update the overall working hours and minutes.
The problem is, when the user clicks the save button, a postback happens, but it is not because of save button's action but because OnTextChanged has fired. The user believes that the saving has gone well until he/she access the page again and doesn't find his/her data. It's next to the impossible to explain to user that they need to click twice because the first time the textbox loses focus and the second time it's the right one.
Is there a way to store the value of the last element that had the focus before the postback occured? I've tried to access the value of __LASTFOCUS, but I'm getting an empty string.
string lastFocus = Page.Request.Params.Get("__LASTFOCUS");
Thanks for helping
If you are trying to grab the last control that lost focus which has AutoPostBack="true", I believe you can get the Name of this control from Request.Form.Get("__EVENTTARGET"). This form variable contains the ID of any control invoking postback (in most, if not all, scenarios).
I have a similar situation with a GridView with an arbitrary amount of textboxes, each with AutoPostBack on and OnTextChanged event handlers. What I wanted to do was be able to tab out of a textbox, postback, then restore focus to the textbox that had focus before postback e.g. the textbox that I tabbed to.
This is what I ended up with:
function RestoreFocus(source, args) {
var val = $("#<%=postbackFocusID.ClientID %>").attr("value");
var el = document.getElementById(val);
if (el != null)
el.focus();
}
function PersistElementThatHasFocus(source, args) {
$("#<%=postbackFocusID.ClientID %>").attr("value", document.activeElement.id);
}
function AddRequestHandler() {
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_endRequest(RestoreFocus);
prm.add_beginRequest(PersistElementThatHasFocus);
}
The postbackFocusID is just an asp:HiddenField.

How can I dynamically create an ASP:Button that causes no postback inside an UpdatePanel?

I have a page some 2 ASP Tabs and with an UpdatePanel on the first tab. Inside the update panel (on page_load), I dynamically create a table that contains rows with cells for an image, some text, and an ASP:Button. I'd like the button, when clicked to switch tabs from the first to the second. Instead, all it does is refresh the updatepanel it resides in. How can I stop it from behaving that way? How do I get it to perform a function of my own design, instead of posting?
Thank you,
You can add javascript click event and stop it to do post back by returning false;
In Code behind, where you add button dynamically.
btnChangeTab.Attributes.Add("onclick", "return YourJavascriptFunction();");
In Client side.
<script type="text/javascript">
function YourJavascriptFunction()
{
//Your javascript code here
return false; //the will stop from postback
}
</script>

ASP.NET drop down selected index not changed event

There is an event onSelectedIndexChange for DropDownList in ASP.NET which triggers when a selected index is changed for a dropdown.
I have encountered a situation where I need to trigger similar kind of event when SelectedIndex of DropDown does not change upon selection.
I am totally puzzled what to do in such a case?
Any help/references will highly be appreciated.
Thank you.
I think that is normal. The event is SelectedIndexChanged and you said you selected the same item that was previously selected before. So the index remains the same, not changed, and the event won't fire. May be you look at OnClick.
The issue is that you have not changed the index when you clicked the second time, so the dropdown is still waiting for you to change it
Assuming you have another server-side control on your page that causes a postback, you could write a routine in the postback event for the other control that compares the current selection with the previous selection and fire a custom-event (or the routines you want to happen) if the value has not changed.
That said, I have to imagine there's an easier way to accomplish the overall goal you're trying to achieve, but you'll have to be a little more specific in your question.
UPDATE
I have to assume that you are using the value from the dropdown when you are processing the form. Why not start off with the dropdown hidden and the linkbutton shown? Just select a default from the dropdown list and allow the user to change it as needed.
Here's a fiddle showing that behavior: http://jsfiddle.net/rjaum/
That's fairly easy.
You can achieve this using javascript/jquery/server side code etc. Assuming user does click the control.
Something like this on pageLoad
PageLoad()
{
YourDropDownList.Attributes.Add("onclick","javascript:CallHelloWorld();return false;");
}
Then on server side you can decorate a method with WebMethod attribute
[WebMethod()]
public static string HelloWorld()
{
return "Hello foo";
}
On your client side aspx you can use jQuery to call your webmethod
<script language="text/javascript">
function CallHelloWorld()
{
// Call HelloWorld webmethod using jQuery $.ajax
}
</script>
Edit
You can use a radiobutton list instead of dropdownlist. That way, on client side you can check the event when the radio button is clicked that it is checked or not (if its checked fire your event).
Edit
Also try looking at this thread if you want to use dropdown list specificallyFire event each time dropdown list is selected with JQuery
assign an a event handler to the selected index changed event and set autopostback to true
in markup
or code behind
mydropdownlist.SelctedIndexChanged += NameOfMethod
the handler is then defined like this
protected void NameOfMethod(object sender, EventArgs e)
{
//your code here
}
update
by definition the selectedindexchanged event would only fire when the index changes. if you want to force the postback that will require some javascript. here is an example of how to do that with jquery
$(function() {
$('select').change();
});

ASP RadioButton Client Event Not Triggering

I'm dynamically generating radio buttons in my code behind and assigning javascript to them as they are created. This javascript will change the value in a hidden field for when a postback is eventually triggered (autopostback on the buttons is disabled). I am using the exact same method with ASP ImageButtons and it works fine but when I do it with the radio buttons the event never triggers the Javascript. I suspect that I may be using the wrong event name but I have tried several (onclick, onCheckedChanged, etc).
Here is a sample of the VB.NETcode - how come this works fine with my button but not my radiobutton!
//This is my hidden field
ClientScript.RegisterHiddenField(Me.UniqueID & "_someVariable", "")
Dim radDefault As RadioButton = New RadioButton()
radDefault.GroupName = "radio buttons"
radDefault.AutoPostBack = False
//This adds the Javascript to set the hidden field with an onClick event
radDefault.Attributes.Add("onClick", "document.forms[0]." & Me.UniqueID & "_someVariable.value='0';document.forms[0].submit();")
The code is simplified as the button generation is actually through an iterator but the same properties are given to each generated radio button.
the postback caused by pressing the button was actually clearing the value of the hidden field (different behaviour from assigning the javascript to a button)

Resources