I have the following aspx code
<asp:TextBox ID="uname" runat="server" AutoPostBack="True"
ontextchanged="uname_TextChanged"></asp:TextBox>
in code behind file
protected void uname_TextChanged(object sender, EventArgs e)
{
Response.Write("Called on postback");
}
As per my assumption due to autopostback if I write anything in the textbox a postback will occur, but its nor occuring now, what could be the reason?
Normally there are more than 1 event handler for an event like for a control, which event will be triggered if autopostback occurs.?
You said As per my assumption due to autopostback if I write anything in the textbox a postback will occur.
That is wrong. It will fire text changed event when your focus from textbox will be out. So when you type something and press Tab key then only your TextChanged event will be triggered.
If you want to trigger TextChanged event when you type something then you should call it from javascript using OnKeyDown event. see below code sample :
<asp:TextBox ID="uname" runat="server" AutoPostBack="True"
OnKeyDown="TextChanged(this)" OnTextChanged="uname_TextChanged"></asp:TextBox>
<script type="text/javascript">
function TextChanged(control) {
$(control).change();
}
</script>
Now when you type anything in your textbox it will call TextChanged method of javascript and this method will trigger uname_TextChanged event.
Assumption:
If your textbox control is inside UpdatePanel then also your change event cannot be triggered. In such a case you should define trigger for text box. as mentioned below :
<asp:UpdatePanel runat="server" ID="up1">
<ContentTemplate>
<asp:TextBox ID="uname" runat="server" AutoPostBack="True"
OnKeyDown="TextChanged(this)" OnTextChanged="uname_TextChanged"></asp:TextBox>
</ContentTemplate>
<Triggers>
<asp:PostBackTrigger ControlID="uname" />
</Triggers>
</asp:UpdatePanel>
Q : which event will be triggered if autopostback occurs ?
Answer: Normally, for all the events for which contents are changed between the post server, AutoPostBack requires. But it wont be triggered until you define the event for that.
For example if you set the AutoPostBack property of the DropDownList to true, and if you don't specify the OnSelectedIndexChanged event then it will not trigger this event. But your page will be post back when you change the value.
Same thing happens in case of TextBox, CheckBox, RadioButton etc...
Hope it is enough to understand.
Try by changing the ontextchanged to OnTextChanged and try. and after entering the text in textbox try to click the mouse on the page sure it works.
MSDN states that the AutoPostBack is only raised when the control loses focus:
Gets or sets a value that indicates whether an automatic postback to
the server occurs when the TextBox control loses focus.
...
Use the AutoPostBack property to specify whether an automatic postback
to the server will occur when the TextBox control loses focus.
Pressing the ENTER or the TAB key while in the TextBox control is the
most common way to change focus.
However, a test showed that you need to enter a text first for the PostBack to occur. After I entered some text and tabbed out of the TextBox, the PostBack was done and the TextChanged event was raised. After clearing the text and tabbing out of the TextBox, the AutoPostBack was also done, so it does not depend on whether the TextBox is empty or not.
To address also the second part of your question: which event is raised during the PostBack is decided upon by the ASP.NET framework during the initialization phase of the PostBack. E.g. if the text of the TextBox that is contained in the Form values differs from that stored in the ViewState, the TextChanged event is raised. This explains why the TextChanged handler is called even if the AutoPostback was initiated by the losing the focus.
Related
I'm trying to run my OnCheckedChanged inside an itemtemplate, but it is not firing. What I did was I typed the OnCheckChanged in the asp:CheckBox tag and also typed the entire method manually. Would this affect the process??
<asp:CheckBox runat="server" ID="uoCheckBoxTagtoVehicle" OnCheckedChanged="ChkChanged" AutoPostBack="true" Width="50px" />
and my event:
protected void ChkChanged(object sender, EventArgs e)
{
uoHiddenFieldVehicle.Value = "1";
}
Note: I'm using Visual studio 2008
Since your control is inside a GridView (since you said ItemTemplate I assume you do) you can't use your approach to attach the event as you did. Because there will be multiple check boxes once you populate the GridView. Therefore, do the following
In you GridView's DataBinding event find the CheckBox by ID (use FindControl method)
Then attach the event OnCheckedChanged to the method you've written
Maybe you are databinding the page also on postback. You should do that only ...
if(!IsPostBack)
{
DataBindPage(); // method which databinds your controls like GridView
}
Otherwise you prevent that events are triggered.
I have a DropDownList in my page:
<asp:DropDownList ID="ddlPra" ClientIDMode="Static" CssClass="chosen-select" runat="server" OnSelectedIndexChanged="Practice_SelectedIndexChanged"></asp:DropDownList>
Code Behind:
protected void Practice_SelectedIndexChanged(object sender, EventArgs e)
{
MessageBox.Show(ddlCli.SelectedItem.Text);
}
I also have an UpdatePanel which has a GridView that displays some data with links. The issue I am having is when the page loads and I change the option from the select drop down, I don't get an alert but when I click on anything inside theUpdatePanel` the alert is displayed.
How do I fix it so that the DropDownList works independent from the UpdatePanel
Why DropDownList event fires after another event?
Because you have not set AutoPostBack="true", it is false by default. That means that it will not post back immediately after the user selected another item. But the event will be triggered on the next postback anyway, independent of the control that caused it.
I'm working on a ASP.NET/C# project, and have a GridView control. One of the columns is a TemplateField/ItemTemplate with an ImageButton inside. During the OnClick event, I make a panel visible. When doing this with a regular ImageButton, the page reloads and the panel is visible. This doesn't happen with my ImageButton inside of the GridView. Does anyone know how I can make it do so, or why this is the case?
Thanks for your time, please let me know if you have any questions.
Here's the relevant asp definition
<asp:TemplateField ItemStyle-Width="90px" ItemStyle-VerticalAlign ="Bottom" ItemStyle-HorizontalAlign ="Center" HeaderText="Add Alias">
<HeaderStyle Font-Bold="True" Font-Size="11px" VerticalAlign="Bottom"/>
<ItemTemplate>
<asp:ImageButton ID ="btnAddAliasHeader" runat="server" ImageUrl="~/img/AddAlias.gif" onclick="btnAddAlias_Click" />
</ItemTemplate>
</asp:TemplateField>
And here's the C# for the OnClick function.
protected void btnAddAlias_Click(object sender, EventArgs e)
{
ImageButton btnAddAlias = (ImageButton)sender;
GridViewRow row = (GridViewRow)btnAddAlias.Parent.Parent;
int rowIndex = row.RowIndex;
lblSelectedCity.Text = gvResults.Rows[rowIndex].Cells[0].Text;
lblSelectedCountry.Text = ddlCountry.Text;
pnlAddAlias.Visible = true;
}
I added the OnRowCommand event and made the panel visible there, however it still doesn't show up. I think it may have something to do with postback, because if I then click the button outside of the gridview, on the reload then the panel from the button inside the gridview shows up fine.
Edit: I'm an idiot and left out that all of this is happening in an updatepanel.
Buttons, ImageButtons and LinkButtons do not fire Click events when they are in a control template like you describe. (Edit: unless used with the OnClick property of the control) Instead, the containing control fires an event, in the case of the GridView it is a RowCommand event. Use the CommandName and CommandArgument properties of your button to determine the proper action to take in the event handler as shown below:
Markup:
<asp:LinkButton ID="LinkButton1" runat="server" CommandName="DoStuff" CommandArgument='<%# Eval("RecordID") %>' Text="DoStuff"></asp:LinkButton>
Code:
Protected Sub GridView1_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles GridView1.RowCommand
If e.CommandName = "DoStuff" Then
'Do something with e.CommandArgument'
End If
End Sub
The buttons/imagebuttons inside a container such as a gridview (listview, repeater, etc) have their click event bubbled up to the container itself. To make the panel visible, you need to use the command name and command argument properties on the button, and then use the OnRowCommand event of the gridview to dispay the panel
HTH
I'm supposing your event isn't firing - you should use the commandname attribute on the imagebutton - and pick it up on the onrowcommand of the gridview - or register your imagebutton click event in the onrowcreated event.
If the postback is not needed. Sorry if I misunderstood the question. You could instead of using an image button (server control), use a link or regular image wrapped in an a tag and jQuery. This will prevent the postback to the server. Hope this helps.
Click to View Panel
$("#<%=viewPanel.ClientID%>").click(function(e)
{
e.preventDefault();
$("#id_of_panel").show();
});
Hope this helps.
You can user Oncommand Event for gridview rather than using Onclick on the perticular control only you have to pass commandname from the control and check it by e.commandname and do what ever you want to perform
I'm learning asp.net page life cycle.
I find an article on MSDN
http://msdn.microsoft.com/en-us/library/ms178472.aspx
It says that
If the request is a postback, control event handlers are called. After that, the Validate method of all validator controls is called, which sets the IsValid property of individual validator controls and of the page.
And the picture in the article also says validate fires after event handling.
If this is true how can I get status of validator when I handling the event?
In further confirmation of Ben Robinson's answer, it looks like Microsoft updated the documentation after this question was asked. The MSDN article clarifies:
If the request is a postback, control event handlers are called. After
that, the Validate method of all validator controls is called, which
sets the IsValid property of individual validator controls and of the
page. (There is an exception to this sequence: the handler for the
event that caused validation is called after validation.)
This is the correct behavior. You can test this with a simple page:
Markup:
<form id="form1" runat="server">
<asp:TextBox ID="txtTest" runat="server" ValidationGroup="test" OnTextChanged="txtTest_TextChanged" />
<asp:CustomValidator ID="cvTest" runat="server" ValidationGroup="test" ControlToValidate="txtTest" ValidateEmptyText="true" OnServerValidate="txtTest_Validate" />
<asp:Button ID="btnTest" runat="server" Text="Test" ValidationGroup="test" OnClick="btnTest_Click" />
</form>
Code-behind:
protected void txtTest_TextChanged(object sender, EventArgs e)
{
}
protected void txtTest_Validate(object sender, ServerValidateEventArgs e)
{
}
protected void btnTest_Click(object sender, EventArgs e)
{
}
Set breakpoints on all the events. Run the app, change the text in the box, and click the button. You should observe that TextChanged fires first, then Validate, then Click.
Validators are validated before their server side event handlers are fired, you can rely on e.IsValid in them, this definitely works, many people use it all the time.
I'm not certain the picture is correct, as by the time you are in the click event of a button, the validators have fired. You call Page.IsValid to check and see if any validators have failed.
I've never used it, but the Page class also contains a collection of validators (Page.Validators). You might be able to use that to determine which specific validators are failing.
Page_Load event fires before the Control's Server Event. You can validate the Page with Page.IsValid in Page_Load event and leave the Page Cycle to handle the rest. This is commonly used in most of the projects.
I have a GridView with an asp CheckBox in a TemplateField. The TemplateField is defined as follows:
<asp:TemplateField HeaderText="HeaderName">
<ItemTemplate>
<asp:CheckBox ID="checkBoxId" runat="server" OnCheckedChanged="MyCheckChangedMethod" AutoPostBack="true"/>
</ItemTemplate>
</asp:TemplateField>
When I run my web project with a breakpoint inside MyCheckChangedMethod and click the checkbox nothing happens. The breakpoint is not hit. My Visual Studio debugger is running.
Additionally, I have AutoEventWireup = True in my page defnition so I don't have to manually hook up the event. I have never had a problem doing it this way before. I have a button on the same page setup the exact same way with a click event and the breakpoint gets hit fine in that.
Any ideas?
The problem occurs when DataBind is called before the control event is firing.
If you call DataBind in Page_Load put it in
if (!isPostBack) {} and call DataBind in the event handler itself.
You need to add AutoPostback = True in asp:CheckBox tag.
The postback event for the checkbox control won't fire correctly because it's within a GridView that mangles the ID of the control.
If you need the Checkbox to reflect data you can use the CheckBoxField object and bind that way.
If you need it perform an action for the row, you may want to look at the ButtonField object using the CommandName property and the RowCommand event.
There are ways to access the checkboxes within the GridView server side.
try:
<asp:CheckBox ID="checkBoxId" runat="server" AutoPostBack=true OnCheckedChanged="MyCheckChangedMethod"/>
Make sure that the aspx page has CodeFile="YOUR_FILE.aspx.cs" at the top.
Also see to it that your function MyCheckChangedMethod is defined as
Function should have object sender, EventArgs e.
public void MyCheckChangedMethod(object sender, EventArgs e)
{
bool b = false;//your data here
}
Also make sure that the web.config has debug set to true (think already done).