Note that there are some explanatory texts on larger screens.

plurals
  1. POWhy do unrelated (autopostback) methods get called when an Asp.Net ListBox autopostback method is invoked?
    text
    copied!<p>I'm sure this is simple but it's driving me nuts.</p> <p>I have a ListBox on my page to show artists, which calls a method when the index is changed, and a button which loads an artist from that list in another page when clicked:</p> <pre><code>&lt;asp:ListBox ID="lbArtists" runat="server" Rows="1" AutoPostBack="true" OnSelectedIndexChanged="ShowArtistsWorks" /&gt; &lt;asp:Button ID="btnEditArtist" runat="server" Text="Edit the artist" OnClick="LoadArtist" /&gt; </code></pre> <p>Further on, I have a similar list of links, which also has an autopostback method:</p> <pre><code>&lt;asp:ListBox ID="lbLinks" runat="server" Rows="1" AutoPostBack="true" OnSelectedIndexChanged="LoadLink" /&gt; </code></pre> <p>The problem is, when I invoke <code>ShowArtistsWorks()</code> by clicking <code>btnEditArtist</code>, the <code>LoadLink()</code> method also gets called. Why is that happening? Why would that get called when I haven't changed the index on the <code>lbLinks</code> ListBox? It shouldn't be going near that method.</p> <p><strong>EDIT:</strong> (relevant) Code-behind methods (</p> <pre><code>protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack){ GetArtists(); // populates artists listbox GetLinks(); // populates links listbox } } protected void LoadArtist(object sender, EventArgs e){ if (lbArtists.SelectedValue != "") Response.Redirect("Artist.aspx?id=" + lbArtists.SelectedValue); } protected void LoadLink(object sender, EventArgs e) { if (lbLinks.SelectedValue != "") Response.Redirect("Link.aspx?id=" + lbLinks.SelectedValue); } </code></pre> <p><strong>EDIT #2:</strong> I could easily kludge a fix for this in the individual methods to stop them happening when they shouldn't, but I want to understand why methods that I don't call, and that only get called from one place, get invoked inadvertently.</p> <p><strong>ACCEPTED ANSWER:</strong> Even though Boon (now CRice) got in first with an explanation and a solution, I decided to accept Jeff's more thorough explanation because that was what I wanted, a more in-depth analysis. Thanks to everyone who answered.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload