I have a page with textboxes and buttons. When the page loads, often times, focus is in one of the textboxes and I don't want this to happen. However, I don't want to use something like setfocus in the page load event because then when buttons are clicked the page will jump. How do prevent the textboxes or any controls for that matter of getting focus on page load?
strange. by default, the page will not focus on any form input unless you set focus on it.
I think you have to cancel all focus by Setfocus on page.
protected void Page_Load(object sender, EventArgs e)
{
// make sure its not a postback
if (!IsPostBack)
{
// your code
InitForm();
InitBlaBlaBla();
SetFocusOnThis();
SetFocusOnThat();
// cancel all focus
Focus();
}
else
{
// this is a postback,
// set focus on control which make post back
Control control = null;
if (!string.IsNullOrEmpty(Page.Request.Params[postEventSourceID]))
{
control = Page.FindControl(Page.Request.Params[postEventSourceID]);
}
else
{
// if postEventSourceID is null, its a button
// find it by iterating all controls
foreach (string ctl in Page.Request.Form)
{
Control c = Page.FindControl(ctl);
if (c is System.Web.UI.WebControls.Button)
{
control = c;
break;
}
}
}
// finally
control.Focus();
}
}
basically what I want to do is when
the page loads as the result of
redirecting from another page, don't
set the focus in any textboxes, just
load the page normally, but if the
page loads as a result of clicking a
control on the page, keep the focus
on/near that control.
To accomplish this you have to test for post back. If you detect the page has been posted back, you can set focus to the control, as you intend to. Otherwise, the page is not beeing posted back (GET), so you can avoid the focus on the control.
As far as I know, by default, ASP.NET Webforms don't set the focus on any of textboxes. Are you sure you don't have some code-behind method setting the focus on the textbox?
It turns out that freetextbox controls exhibit this behavior on IE7 and IE6. It is a bug they are investigating.
Related
I have a usercontrol containing a few textboxes and a submit button which runs inside a larger page, I have a few panels in the usercontrol so that when the user clicks submit the panels I toggle the visibility of the form panel with a panel saying "you have submitted". The problem I am having is that when the form is submitted it refreshes the whole page. I am wondering if there is any quick modification I can make to the usercontrol to have it only refresh itself without rewiring the form in ajax?
protected void Button1_Click(object sender, EventArgs e)
{
DatabaseConnection connection = new DatabaseConnection();
//Verify if entry exists
if (CheckValid())
{
//Register data
pnlSuccess.Visible = true;
}
else
{
pnlDejaRepondu.Visible = true;
}
pnlForm.Visible = false;
}
You can enclose content of the user control into an UpdatePanel.
UpdatePanel will cause partial postback of the user control content only, leaving the rest of the page intact.
I have an AjaxToolkit TabContainer control with a number TabPanels. Each TabPanel has a different UserControl in it to display some information. Some of these UserControls have either a LinkButton or a GridView with a command button in them. The TabContainer has AutoPostBack="false" and this is how I would like to keep it.
When you click on the LinkButton or command button in the GridView the expected events fire and the code runs. But when the page is returned the initial tab is selected again (and not the tab the user was previously viewing).
So my question is: Is there a way to maintain the selected tab when some child control causes a postback?
Some constraints:
I do not way to turn AutoPostBack on. This means the linked solution for this question question is no good in this case.
The UserControls are not always used in a TabContainer/TabPanel so the solution can not assume that this is the case.
The solution needs to be fairly robust and straightforward as there could be different devs working on this code.
I solved this problem by creating my own control that inherits from TabContainer, then overriding LoadClientState() like this:
protected override void LoadClientState(string clientState)
{
base.LoadClientState(clientState);
// If post back was caused by control on a tab, make that tab the active one
if (!string.IsNullOrEmpty(this.Page.Request.Params["__EVENTTARGET"]))
{
foreach (string ctlName in this.Page.Request.Params["__EVENTTARGET"].Split('$'))
{
if (this.FindControl(ctlName) is TabPanel && this.Tabs.Contains(this.FindControl(ctlName) as TabPanel))
{
this.ActiveTab = (this.FindControl(ctlName) as TabPanel);
break;
}
}
}
}
This finds the TabPanel on which the control causing the postback resides, then makes that the active panel.
I got this from another forum. You set this in the pageload. I don't know if that would help with them being set to AutoPostBack=false, but if you haven't given up on it yet, I hope this helps
if (ViewState("ActiveTabIdx") != null)
{
activeTabIndex = Convert.ToInt32(ViewState("ActiveTabIdx"))
if (activeTabIndex != null)
{
TabContainer1.ActiveTabIndex = activeTabIndex;
}
}
you need to add ActiveTabChanged event for tab container and you can keep active tab index in view state, and on page load just check if it is not null then set it as Active tab index.
protected void TabContainer1_ActiveTabChanged(object sender, EventArgs e)
{
ViewState["ActiveTabIndex"] = TabContainer1.ActiveTabIndex;
}
PageOnLoad Event code
if (!(ViewState["ActiveTabIndex"] == null) )
{
TabContainer1.ActiveTabIndex = (int)ViewState["ActiveTabIndex"];
}
Make sure to add following attributes in TabContainer tag
AutoPostBack="true" OnActiveTabChanged="TabContainer1_ActiveTabChanged"
In Page_Load I populate an asp:Table with a grid of images. I have a button that when pressed I would like it to repopulate the page with different images.
However it appears that when the button is pressed Page_Load is called again, followed by the script specified by the button. I thought that I could simply set a variable in the button script which is checked during Page_Load, but this will not work.
What is the most asp.netish way to approach this? Should I be populating my table somewhere other than in Page_Load, or should my button be doing something different?
Your button event gets called after page load. As such, you should put your button code in there.
I'm not terribly sure why you'd try to stuff all of your event code into Page_Load, but it's best to keep it separated.
GOOD
protected void Page_Load(object sender, EventArgs e)
{
MethodThatDynamicallyCreatesControls();
}
protected void MyImage_Click(object sender, EventArgs e)
{
MyImage.Property = newValue;
MyImage2.Property = newValue2;
PopulateTables(newValues);
}
BAD
protected void PageLoad(object sender, EventArgs e)
{
if (Page.IsPostBack)
{
//Check to see if "MyButton" is in the Request
// if it is, it's the button that was clicked
if (Request["MyButton"])
{
MyImage.Property = newValue;
MyImage2.Property = newValue;
PopulateTables(newValues);
}
}
}
As rick said, it's all a matter of understanding the postback.
page_load gets fired every time the page is refreshed. however in many cases, you only want certain things to happen on the first time a page is loaded. in your case, you want the default images to load. by putting all 'one time' events for a page load in a
if (!Page.IsPostback )
{
}
it will only fire on the first time the page is loaded. this is what you want to load your first set of images.
Then in your button click event (which triggers a postback), the code within the if statement will not execute again. and you can load your second set of images in your button's event handler.
That button you're using should call a method in your code behind,so you can know that the button is was clicked, ex:
protected void Important_ButtonClicked(Object sender, EventArgs e)
{
//do what I want to do
}
<asp:Button id="Button1"
Text="MakeChanges"
OnClick="Important_ButtonClicked"
runat="server"/>
Actually I understand what your problem is now, seems like you just have values being set in your page load with no condition check in you page load, so every time you have a postback it refreshes the page to original state, the reason for that is because everytime you trigger a refresh(postback) on the page, the pageload method is invoked, so you need to set original setting in your page load,but have them in the condition, as
if(!Page.Postback) which gets triggered the first time you visit this page. Which means this is where your defaults go and if(Page.Postback) is where your always true things should go. ex:
protected void Page_Load()
{
// this is where I want things to always happen whenever the page is loaded
//for example, no matter what happens I want a certain image in the background
if(!Page.Postback)
{
//set my values for the first and only time
}
else //hint Page.Postback
{
//you can play with the page here to make necessary changes
//but Button click method will still be invoke so thats where button click
//changes should be made
}
}
A PostBack happend when the page is reload. The first page load, Page.IsPostBack has value false. When an event happend, Page.IsPostBack has value true.
So doing the thing like this will definitely works
void Page_Load()
{
if (!Page.IsPostBack)
{
//do your first time binding data
}
How to: Create Event Handlers in ASP.NET Web Pages
EDIT:
Your state change events are not going to fire correctly if you re-bind controls(ie:DropDownList) data on every postback.
void Page_Load()
{
if (!IsPostBack)
{
//load your data
}
}
Using VS2005, ASP.Net 2.0, AjaxControlToolKit
I have a LinkButton in a Panel that contains an UpdatePanel with a GridView. The link button is outside the UpdatePanel. The OnClick event has this code:
protected void lnkOk_Click(object sender, EventArgs e)
{
foreach (GridViewRow row in grdProductSearch.Rows)
{
CheckBox chk = row.Cells[0].Controls[0] as CheckBox;
if (chk != null && chk.Checked)
{
// ...
}
}
Server.Transfer(Page.Request.RawUrl);
}
I need it to pass the selected values of the grid back to the Parent page in a post back. But all it does is close the Panel.
Any ideas why this is happening? or how can I achieve what I am trying to do?
Try putting everything inside the UpdatePanel. Sometimes this control messes up the page normal behavior.
I've seen several times that UpdatePanel control affect somehow (it's difficult to say where and how) the javascript of the page. For example, When you have the UpdatePanel declared as ChildrenAsTriggers="false" and declared AsyncPostBack triggers, if you have a Validation Summary inside, it never shows the validation errors done in the server.
I am using an ASP.NET ModalPopupExtender on a page and would like to prevent the dialog from hiding when the user presses the ok button in certain conditions. But I can't seem to find a way.
What I am looking for is something like this
ajax:ModalPopupExtender
...
OnOkScript="return confirm('You sure?')"
...
if confirm is false, then the modal dialog doesn't disappear.
From my understanding in your specific situation you would not wire up the button, and just wire up a script to handle the conditional, then you can close it via JS.
The following JavaScript function will allow you to achieve this:
function conditionalHide(clientID)
{
if (confirm('You sure?'))
{
$find(clientID).hide();
}
}
You can wire this up to your asp:Button control in the Page_Load event of your page
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
btnOK.OnClientClick = string.Format("conditionalHide('{0}'); return false;",
panPopup_ModalPopupExtender.ClientID);
}
}
Some notes:
panPopup_ModalPopupExtender is your ModalPopupExtender
The return false; prevents a postback from occurring when the user clicks the button
You could hard-code the ClientID of the ModalPopupExtender, but this introduces an (additional) maintainance headache. The approach shown is the best one that I've found to alleviate this overhead