Executing last action when back button pressed ASP.Net - c#

I have a ListBox with a "list of servers" that has AutoPostBack enabled and an SelectedIndexChanged event attached to it:
protected void lbServerList_SelectedIndexChanged(object sender, EventArgs e)
{
if ( lbServerList.SelectedValue.ToString() != "")
{
Response.Redirect("detail.aspx?Server=" + lbServerList.SelectedValue.ToString());
}
}
Then I have a textbox to add a "server" with a button "btnServertoAdd" (to execute the addition)
protected void btnServertoAdd_Click(object sender, EventArgs e)
{
Response.Redirect("add.aspx?Server=" + tbServertoAdd.Text);
}
Scenario: If I select an item from the ListBox it will go to detail.aspx showing the server specs: Awesome.
Now, If I click back (browser button) and then type something in the TextBox and click btnServerToAdd it will still go to detail.aspx and not to add.aspx as it should....
How can I fix this?
Let me know if more code is needed.

This is occurring because when you click the button, the selected server is also different from the original value (as stored in the view state). Both events are fired, but evidently the SelectedIndexChanged event is fired first and the Redirect skips the rest of the processing.
I can't think of how to not make the SelectedIndexChanged event fire the second time around, so instead what you could do is, instead of Redirecting in the events themselves:
Have a pair of bool member variables in your page class.
Set one to true in each event handler.
In the page OnLoadComplete event, check each and redirect as necessary:
If both are true, redirect to add.aspx.
If one is true, redirect to the corresponding page.
Otherwise don't redirect at all.

Related

With ASP.NET, how can I change what a dynamically-generated button does when pressed?

Right now I'm generating a bunch of information pulled from an API and storing it into strings, and displaying that info into cells in a table. I'd like to have a button on each row that, if the user presses it, will grab the information specific to that row. The goal is to be able to click a button and have that information transferred to another list/table of 'selected' items.
I'm relatively new to ASP.NET in general, and I'm aware of how button 'onclick' methods work when you've manually added the button to a web page yourself, but not how to go about doing so when they're generated through code.
If you create an event handler in your code behind for the button, you can then wire each button up to that event handler. Using the parameters of the handler, you know which button was handled.
public void Button_Clicked(object sender, EventArgs e)
{
var button = sender as Button;
button.DoSomething();
}
And each of your buttons would be attached to the event.
<asp:Button OnClick="Button_Clicked" />

event handling in c# .net winform application which uses sql server

i have a combobox with a list of SQLusers, which have permissions granted from beforehand.
a table PERMISSION_DETAIL with columns username, permission_name consists the details of permissions granted or denied
now when a user selects a SQLuser from combobox then the permissions are shown as a checkbox, like if permission is already granted, then the checkbox appears and its tick is checked, else UNCHECKED.
for this i use:
if(permission is previously granted)
checkbox1.checked = true; // here the Checkbox_CheckChanged event is called, but i dont want to call it.
checkbox1.enabled = false;
now, besides the checkbox, there is a button, on clicking it, the checkbox gets enabled, that is, to modify the permission, the user will click the button.
now the user will tick or untick the checkbox to grant or deny permission and the checkbox change event
will be called, this would be fine.
i want that as the checkbox appears, its tick is automatically checked, but this calls the
checkbox_Checkchanged event, but i dont want to call that event.
i advice you to change Checkbox_CheckChanged event to Checkbox_Click event.
private void Checkbox_Click(object sender, EventArgs e)
{
if ((sender as CheckBox).Checked)
{
MessageBox.Show("checked");
// add role to user
}
else
{
MessageBox.Show("un_checked");
/remove role ffrom user
}
}
You could check if the checkbox is enabled, before doing anything in the EventHandler:
protected void Checkbox_CheckChanged (object sender, ..EventArgs e)
{
//return if not enabled
if(!((CheckBox)sender).IsEnabled) return;
//DO THE REST
}
I think that if you make an event handler for CheckChanged, it should be called always when "check is changed", and you should handle logic thereafter.
The event is going to be called regardless, what matters is how you handle that event. An event has occurred, you can't pretend it hasn't. The only thing you can do is decide whether that event means anything to you at a particular point in time.
For example:
public void chkPermission_CheckChanged(object sender, EventArgs e)
{
bool isChecked = chkPermission.Checked;
if (this.user.HasPermission() == isChecked) { return; }
// otherwise, we need to change some permissions!
}
Analyse whether or not you need to do anything, and go from there. Don't just blindly assume something needs to change because an event fired.
Add a boolean variable, IsCheckboxEventShouldFire, to your form. Set to true initially. In the code that sets the checkbox to checked automatically, also now set IsCheckboxEventShouldFire to false. In the checkchanged event, first check if the IsCheckboxEventShouldFire is true. If it is, run your code. If not, then don't. Set IsCheckboxEventShouldFire to true at the end of the event's code.

Problems with IsPostBack

I have an .aspx page which sends a letter to a customer if a button on that page is clicked. Onclick the page calls itself, so the mail send class is in the same file. However I do not want the mail sent when the page is simply loaded. I want it send the letter when the button is clicked, so, I'm trying with the following code:
void page_Load(Object sender, System.EventArgs e)
{
if (IsPostBack)
{
SendMail();
}
}
But it doesn't work. What am I doing wrong?
Why not use the Button's Click Event then?
What you are talking about is you want to send an email only when a specific button is clicked. Then why not register to it's click event instead of bloating your page_load with extra code?
Button's click event is raised only when that button's click causes a postback. So, that's your best option.
Make an event handler for the button's click event (Just double click the button in Visual Studio's Designer).
Using Page_Load will result in emails being sent out when the user posts back in any circumstance, not just your button click.
Looks like the page does not find the correct event handler for the Page_Load, check the case and correct it to Page_Load
See if this works (replace your page_Load method with the following code):
protected override void OnLoad(System.EventArgs e)
{
base.OnLoad(e);
if (IsPostBack)
{
SendMail();
}
}
You are currently relying on AutoEventWireup functionality to hook up your page events. This is slow and problematic and may be the cause of your issue. The method I gave you overrides Page.OnLoad and should correct the problem as well.
The Page_Load event is raised every time the page is posted, well by means of postback or callback, if you want to use server side events you should call you SendMail method in the button's click event:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack && !IsCallback)
{
/*occurs the first time the page is loaded*/
}
if (IsPostBack)
{
/*occurs every time a postback is raised (e.g. by form submission) */
}
if (IsCallback)
{
/*occurs every time a callback is raised, e.g. by generating callbacks by means of AJAX/
}
}
protected void SendMail_Click(object sender, EventArgs e) { SendMail(); }
Read more at MSDN: ASP.NET Page Life Cycle.

ASP .NET Button event handlers do not fire on the first click, but on the second click after a PostBack

Background: I am customizing an existing ASP .NET / C# application. It has it's own little "framework" and conventions for developers to follow when extending/customizing its functionality. I am currently extending some of it's administrative functionality, to which the framework provides a contract to enforce implementation of the GetAdministrationInterface() method, which returns System.Web.UI.Control. This method is called during the Page_Load() method of the page hosting the GUI interface.
Problem: I have three buttons in my GUI, each of which have been assigned an Event Handler. My administration GUI loads up perfectly fine, but clicking any of the buttons doesn't do what I expect them to do. However, when I click them a second time, the buttons work.
I placed breakpoints at the beginning of each event handler method and stepped through my code. On the first click, none of the event handlers were triggered. On the second click, they fired.
Any ideas?
Example of Button Definition (within GetAdministrationInterface)
public override Control GetAdministrationInterface()
{
// more code...
Button btn = new Button();
btn.Text = "Click Me!";
btn.Click += new EventHandler(Btn_Click);
// more code...
}
Example of Event Handler Method Definition
void Btn_Click(object sender, EventArgs e)
{
// Do Something
}
Page_Load Method that calls GetAdministrationInterface
protected void Page_Load(object sender, System.EventArgs e)
{
if (!Page.IsAsync)
{
List<AdministrationInterface> interfaces = <DATABASE CALL>;
foreach(AdministrationInteface ai in interfaces)
{
placeholderDiv.Controls.Add(ai.GetAdministrationInterface());
}
}
}
Good grief! I knew it was going to be something this stupid. Purely my fault of course and my lack of knowledge in ASP .NET.
After doing a multitude of Google searches and eventually being blocked by Google on suspicion of being a bot running automated scripts, I managed to squeeze in one last search in and stumbled across this article. Already at the point of giving up, I tried my best to read the article without skipping 10 lines at a time or looking for pretty pictures. In the section titled Assigning IDs to Dynamically Created Controls, I read these magical and most joyful words:
If you view the source HTML before you click the not-working button and after you have clicked it, you will notice a small difference. The buttons have different HTML IDs before and after the post-back. I got ctl04 and ctl05 before the post-back and ctl02 and ctl03 after the post-back.
ASP.NET button recognizes events by checking for a value for its ID in the Request.Form collection. (In truth it happens differently and controls do not check Request.Form collection by themselves. Page passes post data to controls by their IDs and to controls that are registered to be notified about post data). ASP.NET does not fire the Click event, because the button's ID has changed between the post-backs. The button you have clicked and the button you see after are different buttons for ASP.NET.
Sure enough, when I viewed the HTML the first time, my button had the ID ctl04$ctl36. After clicking the button, my button had the ID ctl04$ctl33.
So there you have it! All I had to do was set the ID on the buttons and presto! My event handlers are now being called!
Sample Solution:
public override Control GetAdministrationInterface()
{
// more code...
Button btn = new Button();
btn.Text = "Click Me!";
// !!THE BANE OF MY EXISTENCE!!
btn.ID = "The_Bane_of_My_Existence";
// !!THE BANE OF MY EXISTENCE!!
btn.Click += new EventHandler(Btn_Click);
// more code...
}
What a great way to spend two days...
I had the same problem, but the accepted answer here was not causing it. I had a text box and a search button, and clicking the button the first time didn't perform the search. The event handler of the button wasn't being hit. But clicking the button a second time did trigger the event on the server. Here is why:
If you have an <asp:Textbox> with its AutoPostBack set to true, after typing in the text box and then moving to click a button, the text box causes a post-back immediately the moment it loses focus. So the click even of the button doesn't count (the page is already posted-back as a result of the text box's event). That's why when you click the button a second time, it works because the text box is not involved in the second post-back.
Set the AutoPostBackproperty of the <asp:Textbox> to false to fix this issue.
A quick fix is to set an ID to the ASCX control your are loading on a page. For example, if your code is like this:
UserControl SpecsControl = (UserControl)Page.LoadControl("../name.ascx");
SpecsContainer.Controls.Add(SpecsControl);
then you need to add a line (before Controls.Add):
SpecsControl.ID = "Aribtrary_Name";
Then your handler method is fired at the first click.
I was facing the same problem. My button froze after my first click. For me this annoying problem got solved when I disabled the button's EnableViewState attribute.
For me it was the UpdatePanel , my Button and my TextBox were both inside an UpdatePanel , so when I post-back , it caused some weird behavior . It took it outside of the UpdatePanel and that fixed it .
Even i had the same problem. the cause was "localhost:1656/secure/login.aspx?ReturnUrl=%2f".
if the request contain %2f as query string, the first post will not be succeeded even though "%2f" is representing "/".
one way to avoid this by having a condition check in pageload
protected void Page_Load(object sender, EventArgs e)
{
string queryString = Request.QueryString.ToString();
if(queryString == "ReturnUrl=%2f")
{
Response.Redirect("/secure/login.aspx");
}
}
Whilst its hard to know exactly without seeing the full Page_load method it does smell a little bit like the event handlers are not hooking up until the page is reloaded.
eg:
if (IsPostBack) {
// Add handlers here ...
}
I had same problem. And I searched on internet i didnt find a solution. After that i found sample code and I used it. It worked for me. Web site link is below:
http://www.c-sharpcorner.com/UploadFile/abhikumarvatsa/calling-an-Asp-Net-C-Sharp-method-web-method-using-javascript/

combobox in C# not getting populated

I have a windows forms app in C#. Platform is vS 2005.
Following is the piece of code:
namespace HostApp
{
public partial class Form1 : Form
{
private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
{
comboBox2.Items.Add("Apples");
comboBox2.Items.Add("Oranges");
comboBox2.Items.Add("Grapefruits");
}
}
}
I run the app but the fruit names do not show up in the drop down of comboBox2. I am sure I am missing some line of code to "populate" the drop down with the entered values.
Any help would be much appreciated.
Thanks,
Viren
You add the items in the handler for the SelectedIndexChanged event. You need to move the code to InitializeComponent or another appropriate place.
Please check the following things:
You have added AutoPostBack="true" in the combo-box so that the selectedChange event is fired and post back happens.
Make sure you have nothung in ur Page load which refreshed the combo box. You can use IsPostBack to acheive loading of the values.
Your items are being added when the selected item is changed, but as there are no existing items this will never happen. Move those lines to the constructor for Form1 and it'll work.
The code you provided will only add items to comboBox2 when the selection changes in the control that is hooked up to comboBox2_SelectedIndexChanged.
There are two concepts at play here: Control Initialization/Databinding, and event handling.
The code you have written essentially says "If somebody selects something new in the combo box, add these 3 options to the combo box". That would happen every time the selected index changes in the combo box. This, of course, assumes you have even hooked up this event handler to the combo box to begin with. This is event handling.
What you are probably trying to do is initialize the control. This happens when you load the page and want to setup the initial options available in your page controls. Using the Init or Load event is probably where you want to setup the choices in your control. This is also when you would initialize your event handlers to say "When something happens, do this".
Move the code to the Page_Load event ...
The SelectedIndexChanged only fires when the ComboBox index has changed AND AutoPostBack = True.
EDIT: Sorry, it's a Form, I was thinking web ... move to Form_Load
For people having difficulties with autopostback and viewstate, beware of the page_load event.
If have been getting on this page alot when trying to google, so that's the reason i'll post it here.
If you fill your dropdownlist (or any other control) in the page_load method, be sure to write an extra control is there is a postback (triggered when changing value of a dropdownlist).
If you don't make that control, your controls will be refilled.
That mistake took me a while to figure out.
So what i'm saying is
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//fill your controls here
}
}

Categories