tags:

views:

45

answers:

3

Hello fellow nerds,

I have a database (using Sqlite) that has ID has a primary key with autoinc, that loads the values into a listbox control. If I loop through the database normally, adding the values of the database into my listbox, I can't get the ID by using SelectedIndex because the Index will not always be the same as the ID, and the ID will not always be the Index. :( This makes it painful when I want to query to delete the row, based on SelectedIndex.

I want to delete the row by ID, but I have no way of getting that ID with the loop I use (or do I? Help me get creative!). Is there some hidden field type attribute I can use?

Thanks!

A: 

if you want to loop in a listbox you should do it like this

    Dim myBox As New ListBox
    For Each item In myBox.Items
        'do stuff with item
    Next

make sure to have at the project level or class level the option infer ON

Fredou
A: 

You can never rely on SelectIndex parity with your database; you should go with SelectedValue and to use your database ID as ListItem value.

Rubens Farias
+1  A: 

It depends on what you are adding as items to your listbox. If you are just adding plain strings, then there is no way to get back to the ID. What you would need is a class that contains both the ID and the value you want displayed. You display the value by overriding the ToString method. My VB is a bit rusty, but here's a pseudo-example:

Class Item
    Property ID as Integer
    Property Name as String

    Sub New(ID as Integer, Name as String)
        Me.ID = ID
        Me.Name = Name
    End Sub

    Overrides Function ToString() as String
        Return Name
    End Function
End Class

Using the class:

Box.Items.Add(new Item(ID, Name))
For Each Item as Item in Box.Items
    Delete(Item.ID)
End For
Adam Ruth
how would i go about getting, per se, the item id and displaying it? i'm quite lost, as i'm not exactly a vb wiz but an amateur. am fiddling around with what you supplied though! appreciated!
Josh streit
That depends on how you're getting it from the database. If you're querying using a DataTable, for example, you can get multiple fields and read them out: new Item(CInt(row["ID"]), CString(row["Name"]))
Adam Ruth
I'm using Sqlite's SqlReader to get it from the database and insert the items into the Listbox. I'm looking to get the selecteditem's id and name but am having an issue. It'd probably make most sense if I just show you what I wish was working!txt_id.text = box.selecteditem(id)txt_name.text = box.selecteditem(name)
Josh streit
It'd probably be best if you posted a new question with the relevant source code, it's tough to pass code back and forth in comments.
Adam Ruth