2011-02-16 42 views
1

我把一個列表框和一個圖像框。 現在我希望圖像在每次用戶點擊列表中的不同元素時進行交換。它似乎沒有工作ASP。清單和圖片

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 ? 
} 

}

+0

關於你的問題,最好用客戶端代碼完成整個事情:真的不需要完全回發就可以交換圖像。 Google爲「jQuery圖片滑塊」查看更多細節。 – 2011-02-17 14:55:52

回答

2

幾件事情。

1)你應該換行代碼在Page_Load中

if(!IsPostback) 

2)確保對在.aspx的「自動回」屬性設置爲true,在列表框!

編輯

每註釋中的要求,這是需要的原因是雙重的。

  1. ASP.NET的ViewState將處理值的持久性上回發,因此,您可以使用!IsPostback條件,以確保信息只能被綁定一次。這可以防止未來出現任何「古怪」。

  2. 默認情況下,當用戶更改選擇時,ListBoxes/DropDownLists/etc不會自動回發。因此,爲了實際觸發事件,您需要具有執行回發的按鈕,或按照指示更新「AutoPostback」屬性,以確保在用戶進行更改時觸發服務器端代碼。

+0

哇。有效。但爲什麼我不得不把我的網頁放在if(!ispostback)..爲什麼它使它工作? – 2011-02-16 19:40:35