2011-12-02 72 views
1

我是網絡構建新手。我在頁面上有以下列表框。該頁面已啓用查看狀態。列表框選擇更改事件選定索引

<asp:ListBox ID="ExamsList_ListBox" runat="server" DataTextField="Namee" viewstate="enabled" 
      DataValueField="ID" AutoPostBack="true" Height="213px" Width="152px" 
      ViewStateMode="Enabled" /> 

數據是在運行時綁定的數據。我可以看到列表,但listbox.selectedindex總是隻會產生「-1」值,即使我點擊了第10個框。你能告訴我什麼是錯的嗎?

這裏是頁面代碼:

<html xmlns="http://www.w3.org/1999/xhtml"> 
<head runat="server"> 
    <title></title> 
</head> 
<body > 
    <form id="form1" runat="server"> 
    <div> 
    <div> 
     <asp:ListBox ID="ExamsList_ListBox" runat="server" DataTextField="Namee" viewstate="enabled" 
      DataValueField="ID" AutoPostBack="true" Height="213px" Width="152px" 
      ViewStateMode="Enabled" /> 
    </div> 
    </div> 
    </form> 
</body> 
</html> 

和填充數據的代碼是:

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load 
     If IsNothing(CType(Session("Login"), TikoClasses.Login)) Then 
      Response.Redirect("~/default.aspx") 
     ElseIf (CType(Session("Login"), TikoClasses.Login)).Admin = False Then 
      Response.Redirect("~/Loggedin/Welcome.aspx") 
     End If 
     ExamsList_ListBox.DataSource = DataModule.Exams_listall((CType(Session("Login"), TikoClasses.Login)).Inst_ID) 
     ExamsList_ListBox.DataBind() 
    End Sub 

和選擇改變甚至是:

Try 
      Dim k As Integer = ExamsList_ListBox.SelectedIndex 
      Dim tt As List(Of Integer) = ExamsList_ListBox.GetSelectedIndices.ToList 
      Dim t As Object = ExamsList_ListBox.SelectedValue 
      If ExamsList_ListBox.SelectedIndex > -1 Then 
       DataModule.GetExam(CType(Session("Login"), TikoClasses.Login).Inst_ID, ExamsList_ListBox.SelectedValue) 
      End If 
     Catch ex As Exception 

     End Try 

尋找幫助。提前致謝。

回答

3

你需要把你的綁定代碼下!IsPostBack

if(!IsPostBack) 
    ExamsList_ListBox.DataSource = DataModule.Exams_listall((CType(Session("Login"), TikoClasses.Login)).Inst_ID) 
    ExamsList_ListBox.DataBind() 
Endif 

因爲只要你選擇改變時,你的Page_Load事件燒製的第一和您的選擇將丟失。

+0

那麼我應該在哪裏保留這段代碼,它是在頁面加載事件? – surpavan

+0

是的,這應該是在頁面加載事件,但在!IsPostBack條件下。 –

+0

它仍然是一樣的。我將頁面加載事件更改爲:受保護的子Page_Load(BYVAL發件人作爲對象,BYVAL e作爲System.EventArgs)處理Me.Load If(Not IsPostBack)Then ExamsList_ListBox.DataSource = DataModule.Exams_listall((CType (「Login」),TikoClasses.Login))。Inst_ID) ExamsList_ListBox.DataBind() End If End Sub通過這段代碼,它只會觸發0索引作爲結果。 – surpavan

相關問題