surpavan
surpavan

Reputation: 1412

Listbox Selection Change Event Selected Index

I am new to web building. I have the following listbox on the page. The page is enabled view state.

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

The data is data bind at run time. I ma able to see the list, but the listbox.selectedindex always results in "-1" value only even though I click the 10th one in box. could you please tell me what is wrong.

Here is the page code:

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

and the code for filling in data is :

 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

and selection changed even is:

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

Looking for help. Thanks in advance.

Upvotes: 1

Views: 4437

Answers (1)

Muhammad Akhtar
Muhammad Akhtar

Reputation: 52241

You need to put your bind code under !IsPostBack

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

Since whenever your selection is Changed, your page_load event fired first and your selection is lost.

Upvotes: 3

Related Questions