ASP.Net: Problem with calling sequence of Text Change event of Text Box
I have placed a list box and a text box with Selected Index Changed and Text Changed event respectively in an aspx page. Now If I write something in text box and then with out clicking elsewhere select a value in list box, then first Text Changed event of text box is called then selected Index Change event of list box is called. After that again Text Change event of text box is called. Can any body give some insight why this happening??
Below is the markup:
<asp:ListBox ID="ListBox1" runat="server" AutoPostBack="true" OnSelectedIndexChanged="ListBox_IndexChanged">
<asp:ListItem Text="abc" />
<asp:ListItem Text="def" />
</asp:ListBox>
<asp:TextBox ID="TextBox1" runat="server" AutoPostBack="true" OnTextChanged="Text_Changed" />
Code behind:
namespace WebApplication1
{
public partial class _Default : System.Web.UI.Page
{
protected void ListBox_IndexChanged(object sender, EventArgs e)
{
}
开发者_JAVA百科 protected void Text_Changed(object sender, EventArgs e)
{
}
}
}
The problem/issue is that AutoPostBack
works by attaching JavaScript events to your controls. Each browser handles JavaScript a little bit differently, so there's no real guarantee to the ordering.
When I try your code in Google Chrome, for example, the following sequence of events occurs:
- Request sent to server
- ListBox_IndexChanged event gets called
- Text_Changed event gets called
- Response goes back to client
However, in Internet Explorer 8, I noticed the following sequence:
- Request sent to server
- Text_Changed event gets called
- Response goes back to client
- Another request sent to server
- ListBox_IndexChanged event gets called
- Text_Changed event gets called
- 2nd Response goes back to client
This isn't a fault of ASP.NET, but just of varying JavaScript implementations across browsers, I suppose.
If you need to rely on a specific sequence of events, AutoPostBack
isn't going to cut it. Depending on your situation, I might look at implementing my own JavaScript events using a cross-browser compliant library like jQuery. You could programmatically call back to the server by using the __doPostBack()
function.
When a new item is selected the text in the text part of the listbox is replaced with the text of the item. That's why you get the second TextChanged event.
精彩评论