开发者

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:

  1. Request sent to server
    1. ListBox_IndexChanged event gets called
    2. Text_Changed event gets called
  2. Response goes back to client

However, in Internet Explorer 8, I noticed the following sequence:

  1. Request sent to server
    1. Text_Changed event gets called
  2. Response goes back to client
  3. Another request sent to server
    1. ListBox_IndexChanged event gets called
    2. Text_Changed event gets called
  4. 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜