User Control Command Button event doesn't fire the first time - asp.net

I am fairly new to the asp.net and experimenting with it to learn the page life cycle. Here is a problem that I have been unable to resolve for past few days.
I have a hosting page (.aspx). Then I have two user controls (.ascx). The page has a place holder control in which it loads the user controls one at a time based on the application flow. First user control is loaded on application start up. It has a "continue" button. Continue button click loads the Second user control that has two buttons - "Back" and "Submit". Obviously the "Back" button should load the first user control again and Submit button should submit the form data. Pretty simple.
The problem is that the command button event handler that I have on the second user control is not firing the first time. (I have one event handler for both buttons). The load event of the user control fires but then it ignores the button click. If I click it again, then it fires. I re-load the controls on the page in every page_load. Here is some relevent code:
AddPlayer.aspx:
protected void Page_Load(object sender, EventArgs e)
{
PlaceHolder1.Controls.Clear();
// Load the ctlInputPlayer control
Control ctlToAdd = LoadControl("ctlInputPlayer.ascx", null);
if (ctlToAdd != null)
{
_ctlInputPlayer = (ctlInputPlayer)ctlToAdd;
_ctlInputPlayer.SendPlayerData += new EventHandler(ctlInputPlayer_SendPlayerData);
PlaceHolder1.Controls.Add(_ctlInputPlayer);
}
// see if there is player data available in the view State
PlayerData player = (PlayerData)ViewState["Player"];
if (player != null)
{
ctlToAdd = LoadControl("ctlPlayerInfo.ascx", player);
if (ctlToAdd != null)
{
_ctlPlayerInfo = (ctlPlayerInfo)ctlToAdd;
_ctlPlayerInfo.SubmitPlayerData += new EventHandler(ctlPlayerInfo_SubmitPlayerData);
PlaceHolder1.Controls.Clear();
PlaceHolder1.Controls.Add(_ctlPlayerInfo);
}
}
}
ctlPlayerInfo.ascx (second user control):
ctlPlayerInfo.ascx.cs
protected void CommandBtn_Click(object sender, CommandEventArgs e)
{
switch (e.CommandName)
{
case "Submit":
//submitPlayerData will fire here
break;
case "Back":
// editplayer data will fire here
break;
}
}
protected void Page_Load(object sender, EventArgs e)
{
// load control data here....
}
The page_Load fires every time but "CommandBtn_Click" doesn't fire after the first click. I have to do it click it again. It doesn't matter which order I click the buttons.
I appreciate the help. Let me know if more details are needed. Thanks!

You should load your user controls every time in Page_Init and set the ID property.

Related

How to control the visibility of panel in the second page based on the button click in the first page

I want to control the visibility of panel(true/false) in ASP.NET webforms based on a button click. If both the controls were in single page, I could have directly accessed it as panel1.visible = true in the button click event but button and panels are in different pages. On button click, I should redirect to a certain page and a certain panel should be made visible. How to achieve this.?
Here's an example using QueryString
Redirection code to be behind your button
bool show = true; // Change accordingly
Response.Redirect("~/NextPage.aspx?show=" + show.ToString());
Retrieval code to be behind your destination page
protected void NextPage_Load(object sender, EventArgs e)
{
string qString = Request.QueryString["show"];
if (qString != null)
{
MyPanel.Visible = Convert.ToBoolean(qString);
}
}

Form submission without reloading page

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.

focus on a user control inside an aspx page after clicking a button inside the user control

I have a user control inside an aspx page, after the aspx page loads, when I click some button inside that user control, I want the focus to come back to user control after that button click action is complete and the aspx page loads again.
You need to have an event in your user control that will allow the .aspx page to subscribe to that event so that it can set focus to the element in the user control after the form posts back, like this:
public class UserControlClass
{
// Define event that will be raised by user control to anyone interested in handling the event
public event UC_Button1ClickEventHandler UC_Button1Click;
public delegate void UC_Button1ClickEventHandler();
// Mechanism to allow event to be raised by user control
private void Button1_Click(System.Object sender, System.EventArgs e)
{
if (UC_Button1Click != null)
{
UC_Button1Click();
}
}
}
Now in your .aspx page, you need to subscribe to the event in the user control and say what method will actually handle the event, like this:
userControl1.UC_Button1Click += Button1_Click;
Finally, the click event handler needs to exist, like this:
public void Button1_Click(object sender, EventArgs args)
{
// Set focus here to user control element, text box for example
((TextBox)userControl.FindControl("TextBox1")).Focus();
}

Dynamiclly added control i.e panel contains buttons event no firing

protected void container1ActiveTabChanged(object sender, EventArgs e)
{
if (container1.ActiveTabIndex == 0)
{
if (container1.Tabs[0].Controls.Count == 0)
{
container1.Tabs[0].Controls.Add(gdvEmployee);
}
}
if (container1.ActiveTabIndex == 1)
{
pnlEmployeeID.Visible = true;
pnlEmployeeInformation.Visible = false;
}
if (container1.ActiveTabIndex == 2)
{
pnlEmployeeInformation.Visible = true;
if (container1.Tabs[2].Controls.Count == 0)
{
container1.Tabs[2].Controls.Add(pnlEmployeeInformation);
}
}
this event not firing
protected void btnInsertClick(object sender, EventArgs e)
Why is my event not firing
I'm assuming you are adding the control which fires the event dynamically.
The most common cause of this issue is that the control that fires the event is dynamically added on every postback.
This causes the previous instance of the control to be replaced.
This in turn causes the event to get "lost" as the control which triggered the event is now gone.
When an event is triggered it is "queued" and will execute after a page has been reloaded.
Once the page has been reloaded the event is executed.
If you replace/recreate the control on every postback i.e in the page load event, you are destroying the trigger of the event and in turn destroy the event.
Ensure you are only adding the control ones when the page is created the very first time but do not re-add the control when Page.IsPostback is true.
Using dynamic controls requires some knowledge of the page life cycle to prevent confusion and endless hours of debugging.
If you are not adding a control dynamically, please feel free to elaborate where your event is triggered from and how the trigger is implemented. I'm sure we will be able to help you to pinpoint and solve the problem with any additional information you have.
Additional Reading
This explains all about page life cycles and view state.
Understanding ASP.NET View State
I'm just guessing, but you probably add the dynamic controls in the Page_Load stage. This is quite a common mistake. Try doing the same at the Init stage:
protected void Page_Init(object sender, EventArgs e)
{
// Your controls should generate here
}

asp.net: How to get a button to affect the page contents

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
}
}

Resources