checkbox chekced or unchecked does not trigger event - c#

There is an exisiting page I am working on at where I work, and there is a checkbox in the ascx , and it has a CheckedChange event for it in its .cs The problem I am having with that page is that when i run the website and check the box, it never fires the event, instead it goes through the On_Load event and it never pass throgh the event... I am not sure why it is not firing the event...
<asp:CheckBox runat="server" ID="OptionSelected"
OnCheckedChanged="OptionSelected_CheckedChanged"
AutoPostBack="true" />
<asp:Label runat="server" ID="OptionHeader"></asp:Label>
protected void OptionSelected_CheckedChanged(object sender, EventArgs e)
{
//some code here
}
PS: This is a control ascx sorry, I forgot to mention. Also another symptom is that the page where that control is... it refreshes unexpectedly, clears some data (including the checkbox if it is checked) and cant figure out what it is causing it.
Any ideas of the reason why this might be happening? things i should look for?
public PortalInfoPortal myPortal
{
get
{
return portal.GetPortalInfo();
}
}
protected void Page_Load(object sender, EventArgs e)
{
//added this an nothing
OptionSelected.CheckedChanged += new EventHandler(OptionSelected_CheckedChanged);
if (myPortal != null)
{
lblOptionMsg.Text = "(" + myPortal.MaxOptionSelectedCharacters.ToString() + " char max)";
txtMessage.MaxLength = myPortal.MaxOptionSelectedCharacters;
var maxLength = myPortal.MaxOptionSelectedCharacters;
maxCheck.ValidationExpression = #"^[\s\S]{0," + maxLength.ToString() + "}$";
}
//There is no binding of any type here
}

you need to have viewstate turned on to have changed events fire. viewstate is how the server knows what the state of the control was when the page was originally served and before it was posted back. without this information, it doesn't know whether the value has changed. check to see if you have viewstate enabled.

Are you perhaps creating the usercontrol (using Page.LoadControl()) and adding it to the control tree dynamically and then forgetting that those steps need to be performed on every postback? Otherwise, the usercontrol no longer exists on postback and none of its events will be fired.

Related

Why is IsPostBack skipping through my code?

I'm trying to decide using switch case which operation to take where ever section i choose to enter in the page, thus when posting back it will take the right action.
This is the button (Note, this is not the button i'm posting with, rather the one where i enter the section of editing credentials)
<input type="button" value="Edit credentials" onclick="ShowWindow('#EditDetails', 2500); <%WhatToDo = "ChangeUserInfo";%>" />
Code-behind:
public string WhatToDo = "";
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
switch (WhatToDo)
{
case "ChangeUserInfo": ChangeUserInfo();
break;
}
}
}
protected void ChangeUserInfo(){ something }
The posting seems to work, other than the fact that it doesn't run the switch case...
don't know what to do and what am i doing wrong.. If anyone knows what am i doing wrong it'll be great :)
You hook up events in ASP.Net, ASP.Net hides the request and response object for you and wraps it into an Event Driven Architecture . So you don't need to handle the button being pressed in the Page_Load. Instead you need:
Server side button in the .aspx:
<asp:Button runat="server" ID="cmdResubmit" OnClick="cmdAddBooking_Click" Text="Resubmit" />
and an event with the same name as the OnClick in the code behind:
protected void cmdAddBooking_Click(object sender, object e)
{
//put code button code here
SomeClass.value = 123;
SomeClass.StringValue = "1234";
//etc. etc.
}
notice the name of the method matches: OnClick="cmdAddBooking_Click" in the button!
That's it. If you want multiple buttons then add multiple <asp:Button> with multiple event attached to them.
Note:
Clicking a button also triggers a page load (and your event) so any code in the Page_Load event will run on every button click. You can avoid this by wrapping it in if (IsPostBack), this means the code inside this if statement will only run on load not on postback

AutoPostBack not triggering Page_Load

I have an asp ddl setup like this:
<asp:DropDownList ID="attendeeList2" runat="server" AutoPostBack="true" CssClass="tripRegistrationItem" />
c#:
private void attendeeList2_SelectedIndexChanged(object sender, EventArgs e)
{
_mission = new Mission(Int32.Parse(tripList.SelectedValue));
person = new Person(int.Parse(attendeeList2.SelectedValue));
attendeeLabel.Text = person.FullName.ToString();
ClearInputs(tripRegistrationWizard.WizardSteps[1].Controls);
LoadAttributes();
SetInfo();
}
and:
private void InitializeComponent()
{
attendeeList.SelectedIndexChanged += new EventHandler(attendeeList_SelectedIndexChanged);
attendeeList2.SelectedIndexChanged += new EventHandler(attendeeList2_SelectedIndexChanged);
}
What I am experiencing is that the attendeeList2_SelectedIndexChanged does indeed fire when the selected item of the DDL is changed, and the code within the method is executed, however a Page_Load, Page_Init, Page_PreRender... are NOT raised. It is almost like it isn't doing a true PostBack, yet it is running the code. I am needing to do some things in the Page_PreRender in that OnChange event, but can't figure out how to pull it off.
Can someone explain to me what I am doing wrong?
Thank you!
EDIT:
Here is the code that calls InitializeComponent():
override protected void OnInit(EventArgs e)
{
//
// CODEGEN: This call is required by the ASP.NET Web Form Designer.
//
InitializeComponent();
base.OnInit(e);
}
EDIT 2:
I just realized that the client side control I am working with is inside an Update Panel. It appears that when the control is within an Update Panel, it simply does an AJAX refresh, never raising the Page_Load, Page_Init... Once I pulled the control out of the update panel, it now triggers a full Post Back as I was expecting. Not sure why I couldn't find that tidbit of info while searching around, but now I know.
Please try at the page directive to add:
autoeventwireup="true"
some like:
<%# page language="C#" autoeventwireup="true" codefile="yourpage.aspx.cs" inherits="yourclass"%>

LinkButton postback but click event not fired

Hi everyoneThis is my first post on stackoverflow (which btw is by far my favourite site for finding answers). After finally admitting defeat, I'm hoping someone can help me with this problem...
The question has already been asked several times, but none of the suggested solutions I found has helped. Apologies in advance for a lengthy post, but I want to avoid anyone wasting their time on suggesting things I tried already.
The code below worked until recently, and its structure has not been touched since (although unrelated changes were made to the child page). In any event, it suddenly stopped working. Now even the most simplified button won’t fire.
Setup
VS 2008 C#, IIS 7 (no changes in setup since way before it stopped working)
nested masterpage (main + 1 child)
dynamically loaded ucl with datalist in child page
(i.e. MP => nested MP => child page => ucl => datalist => linkbutton)
linkbutton click event also resides in ucl
Problem
On LB click, the postback occurs ok, but the server-side click event never gets hit.
Code
page:
var ctrlX = base.LoadControl("~/somedir/someucl.ascx");
=> loads fine
ascx file (datalist stripped of all but the button):
<asp:DataList ID="dlX" RepeatLayout="Table" runat="server">
<HeaderTemplate></HeaderTemplate>
<ItemTemplate>
<tr>
<td>
<asp:LinkButton ID="btnX" OnClick="btnX_Click" CausesValidation="false" runat="server" />
</td>
</tr>
</ItemTemplate>
<FooterTemplate></FooterTemplate>
codebehind:
protected void btnX_Click(object sender, EventArgs e)
{
// do something
}
things tried
cleaning the solution
digging out a working backup and checking for code changes
(found none affecting the structure or user control)
setting LinkButton CausesValidation true/false
stripping datalist and LinkButton down to bare essentials
adding AddressOf="btnX.click" to LinkButton
wrapping UpdatePanel one at a time with varying settings around usercontrol datalist linkbutton
reattaching eventhandler in usercontrol init / load event:
IEnumerable<Control> controls = Utils.FlattenChildren(dlX);
foreach (var button in controls.OfType(LinkButton)())
{
if (button.ID.Contains("btnX"))
button.Click += new EventHandler(btnX_Click);
}
Wherever I add above code, all buttons are found and the event is attached, but click event doesn't fire ((LinkButton) = LinkButton inside <>; couldn't get it to display right, still struggling a bit with the editor)
.
adding PostBackUrl manually in page load event
comparing the client ids between load/postback events
=> they always match
That's it. Right now, I can't think of what else to try or check (maybe something in the breakpoint context menu on postback?).
Because the ucl loads fine, and the postback is working ok, I suspect the problem is somewhere in the ucl, rather than the child page loading it. But maybe not.
If at all possible, I want to avoid workarounds (I need the button command argument, not shown above, and am not keen on solutions such as jquery with hidden field or query string).
Apart from anything, I would really like to understand what causes this.
Obviously, I'm missing something... Thanks to anyone taking their time reading/helping with this!
======== as requested additional codebehind =======
I've simplified the parent page code to a minimum, dropping all method calls, and as per Eoins suggestion moved the ucl load in the page's init event. The ucl code remains as shown above. The DL and LB show up fine, and on click the postback is triggered, ucl page load event is hit, but as before, the server click event is not hit.
protected override void OnInit(EventArgs e)
{
var ctrlX = base.LoadControl("~/someucl.ascx");
if (ctrlX == null)
return;
DataList dlX = (DataList)ctrlX.FindControl("dlX");
if (dlX == null)
return;
DummyCollection x = new DummyCollection();
x.Add(null); // ok since the test LB does not draw on the datasource
dlX.DataSource = x;
dlX.DataBind();
pnlX.Controls.Add(ctrlX);
base.OnInit(e);
}
var ctrlX = base.LoadControl("~/somedir/someucl.ascx");
Where exactly does this code live on your page?
You'll need to make sure you're creating it and adding it to the control collection early enough in the page lifecycle so that on subsequent postbacks its created & wired up in time. I.e. in the oninit event.
protected override OnInit(...)
{
base.OnInit(...);
var ctrlX = base.LoadControl("~/somedir/someucl.ascx");
this.Controls.Add(ctrlX);
}

Gridview Rowcommand event firing but show hide controls including Gridview not happening

Here is what I am trying to do in two simple steps:
1) New Row (trNewPost) which has table inside and controls in it to add new post or to update existing post.
Default Visible=false;
2) Add Button to make above row visible = true;
3) trMyPosts has Gridview in it and displays all the posts.
Default visible = true.
When user click on editing any row of the gridview (RowCommand event) I just want to hide this grid (trMyPosts) and show trNewPost.
That's all. events firing, but nothing happening.
I think you've got viewstate problem.
One of the things you can do is this :
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
// do things here
}
}
Because whenever anything happens, the page posts back. By encapsulating your Page_Load with ! Page.IsPostBack, you prevent those things from happening over and over again.
Now, if your variable is a global variable, you will have this same problem. Consider instead using a Session variable.
Also, I just wanted to show you this piece of code just in case :
protected void HideShowClicked(object sender, EventArgs e)
{
// toggle the visibility of the control
// (that is, if visible then hide, if hidden then show)
myControl.Visible = ! myControl.Visible;
}

Determine when Postback occurs because of a textbox being changed

I've got a usercontrol that has a <asp:TextBox> with autopostback set to true. When the user types text in and moves off the textbox, asp.net fires a postback event. However, it isn't handled specifically by the textbox, but is instead simply a postback - the page_load fires and then life goes on.
What I need is a way to know that this textbox fired the event. I then want to fire my own custom event so that my main page can subscribe to it and handle the event when the textbox changes.
At first I thought I could capture the sender - I was assuming that the sender would be the textbox, but it appears to be the page itself.
Anyone have any thoughts?
I think you're missing something, so I want to explain it step by step :
your textbox should be something like that :
<asp:TextBox runat="server" ID="TextBox1" AutoPostBack="true"
OnTextChanged="TextBox1_TextChanged"></asp:TextBox>
and in your codebehind you shhould have an event like that :
protected void TextBox1_TextChanged(object sender, EventArgs e)
{
string str = TextBox1.Text;
}
NOTE : if you want to attach your event in code-behind you can do this by :
TextBox1.TextChanged +=new EventHandler(TextBox1_TextChanged);
but if you talking about custom controls, you should implement IPostBackDataHandler interface to raise events.
Is this i dynamically created usercontrol or textbox? If so you have to recreate that control in the page_load event and the event should be fired on the textbox as normal.
The page load sender will always be ASP.default_aspx because the page is what is calling that event.
You can hook up to the even OnTextChanged where that sender would be the textbox that has changed or caused the post back.
Keep in mind the page load will always fire before any of the events on the controls.
This is potentially something that could be overlooked, but do you actually have an event coded for the textbox's TextChanged event? If you have it set to autopostback but never actually created an event for it, you're only going to get your page load and other related events.
As alluded to in other answers you need to handle the 'OnTextChanged' event.
<asp:TextBox ID="TextBox1" runat="server" OnTextChanged="TextBox1_TextChanged"></asp:TextBox>
private void TextBox1_TextChanged(object sender, System.EventArgs e)
{
TextBox txt = (TextBox)sender;
string id = txt.ID;
switch(id)
{
case "TextBox1":
break;
}
}

Categories

Resources