[RESOLVED] listbox SelectedIndex problem
hello everyone,
I'm trying to retrieve the selected index of a listbox, but every time i do, i just get -1. here is my code:
Code:
Try
Dim DeleteID As String = SectionList.SelectedIndex
MsgBox(DeleteID)
Catch ex As Exception
lblWarning.Text = ex.Message
End Try
The listbox is filled from a dataset, in the code behind the code. here is that code:
Code:
Private Sub FillListview()
Dim myConnString As String = "Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\AppStore.mdf;Integrated Security=True;User Instance=True"
SectionList.Items.Clear()
Dim userName As String = Session("MyUserName")
Dim TeacherID As String = GetTeacherID(userName)
Dim ds As New DataSet()
Dim SQLDataTable As New DataTable
Dim SQLCon As New SqlClient.SqlConnection
Dim SQLCmd As New System.Data.SqlClient.SqlCommand
Try
With SQLCmd
.CommandText = "FillSections"
.CommandType = CommandType.StoredProcedure
.Parameters.AddWithValue("@TeacherID", TeacherID)
.Connection = SQLCon
End With
Catch ex As Exception
lblWarning.Text = ex.Message
End Try
Dim da As New System.Data.SqlClient.SqlDataAdapter(SQLCmd)
Try
Using SQLCon
SQLCon.ConnectionString = myConnString
SQLCon.Open()
da.Fill(ds)
End Using
Catch ex As Exception
lblWarning.Text = ex.Message
Finally
End Try
Try
FinalCount = ds.Tables(0).Rows.Count
ReDim MyArray(FinalCount, FinalCount)
Dim i As Integer = 0
If ds.Tables(0).Rows.Count > 0 Then
For Each dt In ds.Tables
For Each dr In dt.Rows
MyArray(i, 0) = dr("SectionID")
MyArray(i, 1) = dr("SectionName")
SectionList.Items.Add(dr("SectionName"))
i = i + 1
Next
Next
Else
End If
Catch ex As Exception
lblWarning.Text = ex.Message
End Try
End Sub
Like i said, regardless of which item i pick, i always get -1. anyone have any ideas?
thanks
jason
Re: listbox SelectedIndex problem
never mind. for anyone else who's has this problem, it due to post back. i guess whenever theres a postback, you have to make sure you dont refill the list view, or it wipes what is currently selected. this can be done with this:
If Not Page.IsPostBack Then
FillListview() 'where this is your method to fill the listbox
Else
End If