Click to See Complete Forum and Search --> : Selecting Items from Listbox


jimmyb
02-09-2004, 12:16 PM
I have a database, there's a field called Counter, I want to get this value by selecting an Item from a listbox.

So when I select an item from the listbox, I want the value of the field counter for that item.

I'm doing the following:
sSql = "SELECT * FROM Database WHERE Counter = " & lstData.SelectedItem(lstData.SelectedValue) & ""
--> this gives me it's idex in the listbox.

sSql = "SELECT * FROM Database WHERE Counter = " & lstData.SelectedValue(lstData.SelectedIndex) & ""
--> this errors.

In VB6 it was this.
sSql = "Select * from Database where counter = " & CStr(lstData.ItemData(lstData.ListIndex)) & ""

Can anyone assist with this?

Thanks in advance..!!!

Jim

Phil Weber
02-09-2004, 12:39 PM
How are you assigning the value that you want to retrieve from the listbox? .NET's listbox no longer has an ItemData property, so I'm curious how you're getting the data you want into the listbox; that will determine how you should retrieve it.

jimmyb
02-09-2004, 02:04 PM
Originally posted by Phil Weber
How are you assigning the value that you want to retrieve from the listbox? .NET's listbox no longer has an ItemData property, so I'm curious how you're getting the data you want into the listbox; that will determine how you should retrieve it.

This is some of what I'm doing to add records to the listbox

Dim become As New SqlCommand()
Dim DA As SqlDataAdapter = New SqlDataAdapter()
Dim DS As DataSet = New DataSet()
Dim objcomm As New SqlCommand()
Dim iCounter As Integer

objcomm = cn.CreateCommand()

'Now Specify the SQL Statement.
objcomm.CommandText = "SELECT * FROM Database ORDER BY Name"

'Now open the connection
cn.Open()

'Now Assign the command object to Sql Adapter.
DA.SelectCommand = objcomm

'Now Fill the Dataset with SqlAdapter
DA.Fill(DS, "Database")

Dim pRow As DataRow
Dim sName As String
Dim sAddress As String
Dim sState As String

iCounter = 0
For Each pRow In DS.Tables("Database").Rows
sName = pRow("CustName").ToString()
sAddress = pRow("CustAddress").ToString()
sState = pRow("CustState").ToString()

lstbox.Items.Add(sName & Space(9) & sAddress & Space (9) & sState)
iCounter = iCounter + 1
Next

cn.Close()
DA.Dispose()
DS.Dispose()

Phil Weber
02-09-2004, 02:31 PM
It looks like you're not storing a Counter value in the listbox, correct? If Counter = ListIndex, then you can simply do this:

sSql = "SELECT * FROM Database WHERE Counter = " & CStr(lstBox.SelectedIndex)

If the Counter value will not always be the same as the ListIndex, then you can take advantage of the fact that VB.NET's listbox holds object references, not just strings. For more information, see http://archive.devx.com/dotnet/discussions/031502/ListBoxItemData.asp