Rabu, 04 Februari 2009

VB2005: How To Remove an Item from a ListBox

This is something that seems to come up fairly often in the Forums. Someone wants to test for a particular value in a ListBox and if the list does (or doesn't) contain the value then that item is to be deleted.

One common way of doing this would be to use the Contains function to test if the target character or substring exists in the ListBox.

This isn't a particular difficult task, but the thing that usually catches most beginners out here is that you have to traverse the ListBox items in reverse order. Well, you do if you actually end up deleting any items, anyway. The reason being that if you start from the top and work down, then as soon as you delete an item the ListBox's indices get out of sync and an ArgumentOutOfRange Exception will be thrown and you will get a message along the lines of the one shown below:


In a recent post, a slight variation on this theme was that the check was to be made in one ListBox and if the required search string wasn't found in that first ListBox then not only was the item in the first ListBox to be deleted but also the corresponding item number in a second ListBox was also to be deleted.

Again this is straightforward and the following code will do the job :


Code Copy
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
For i As Integer = ListBox1.Items.Count - 1 To 0 Step -1
If Not ListBox1.Items(i).Contains(TextBox1.Text) Then
ListBox1.Items.RemoveAt(i)
ListBox2.Items.RemoveAt(i)
End If
Next
End Sub

As I say, it's not rocket science, but that traversing upwards trick is something worth knowing for these kind of situations.







source :http://blogs.vbcity.com

-------------------------------------------------------

Trik Gambar Bergerak

Trik Gambar-dimouse

Trik hapus pwd mysql

Trik insertin to db

Trik jadi root dilinux

Trik jam-distatus-bar

Trik Koneksi-ke database

Trik Koneksi-msql-php

Trik lihat-database-mysql

Trik membahas-fungsi-else

Trik member-area