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 ?
}
}
A couple of things.
1.) you should wrap the code in page_load with
2.) Make sure on the .aspx that the “AutoPostback” property is set to true on the listbox!
Edit
Per the request in the comments, the reason this is needed is two fold.
ASP.NET ViewState will handle the persistence of the values on postback, therefore, you can use the
!IsPostbackcondition to ensure that the information is only bound once. This prevents any “oddities” from coming up in the future.By default ListBoxes/DropDownLists/etc do not post back automatically when the user changes a selection. So to actually trigger the event you either need to have a button that does the postback, or update the “AutoPostback” property as I directed to ensure that when the user makes a change that it triggers the server-side code.