i put a list box and an image box.
now i want the image to swap every time the user clicks on a different element in the list. it doesnt seem to work :(

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page 
{
    string[] pictures = { "~/createWii.jpg", 
                               "~/DKC4_wii.png",
                                "~/Donkey-Kong-Country-1.jpg", 
                                "~/DSCallOfDutyBlackOps.jpg", 
                                "~/DSPreviewsCodmw2.jpg", 
                                "~/DSPreviewsAliceInWonderLAnds.jpg",
                               "~/DSPreviewPicross3d.jpg",
                               "~/createii.jpg", 
                               
                           
                            
                           };
    string[] picturesNames = { "picture1", "picture2", "picture3", "picture4", "picture5", "picture6", "picture7", "picture8" };
 
    protected void Page_Load(object sender, EventArgs e)
    {
        for (int i = 0; i < pictures.Length; i++)
	    {
                ListBox1.Items.Add(new ListItem(picturesNames[i],pictures[i]));
         
	    }
    
        Image1.ImageUrl = "~/Donkey-Kong-Country-1.jpg";
        

        ListBox1.DataSource = picturesNames;
        ListBox1.DataBind();
    }
    protected void ListBox1_SelectedIndexChanged(object sender, EventArgs e)
    {
       
   

        Image1.ImageUrl = pictures[ListBox1.SelectedIndex];// it tells me that there is index out of range each time. why ?
  
       
        
    }
}

Server Error in '/WebSite1' Application.
Index was outside the bounds of the array.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.IndexOutOfRangeException: Index was outside the bounds of the array.

Source Error:

Line 41:
Line 42:
Line 43: Image1.ImageUrl = pictures[ListBox1.SelectedIndex];
Line 44:
Line 45:

Dani AI

Generated

— the exception almost always comes from rebinding or repopulating the ListBox on every Page_Load so the selected index is lost (or becomes -1) before the SelectedIndexChanged handler runs. is right that the ASP.Net forum is the right place for WebForms details, but the quickest fixes are simple and local to your code.

What to do

  • Populate the ListBox only once on first load (wrap population/DataBind code in if (!IsPostBack)) so selections survive postbacks.
  • Do not mix manual Items.Add and a separate DataBind call for the same control; pick one approach.
  • Store the image path in the ListItem value (or bind a data source with DataTextField/DataValueField) and use the control's SelectedValue for the image URL instead of relying on parallel arrays and SelectedIndex.
  • Make sure the ListBox has AutoPostBack enabled in the markup so the SelectedIndexChanged event runs immediately.

Minimal examples

  • Markup hint:
    <asp:ListBox ID="ListBox1" runat="server" AutoPostBack="True"
      OnSelectedIndexChanged="ListBox1_SelectedIndexChanged" />
  • Key server-side ideas:
    
    if (!IsPostBack) { /* populate ListBox here once */ }

if (!string.IsNullOrEmpty(ListBox1.SelectedValue))
Image1.ImageUrl = ListBox1.SelectedValue;



Troubleshooting tips
- Add a quick guard: log or breakpoint `ListBox1.SelectedIndex` and `ListBox1.Items.Count` before using them. If SelectedIndex is -1, you repopulated or rebound the control too early.  
- If you keep parallel arrays, validate lengths and always check bounds before indexing.  
- For background reading see the [Page.IsPostBack documentation](https://learn.microsoft.com/en-us/dotnet/api/system.web.ui.page.ispostback?view=netframework-4.8) and the [ListBox.SelectedValue documentation](https://learn.microsoft.com/en-us/dotnet/api/system.web.ui.webcontrols.listbox.selectedvalue?view=netframework-4.8).

Try posting this in the ASP.Net forum

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.