Better way to get value from listview

C

Coderz

Hi,

I am using the code below to get a value from the selected item in my
listview:

Dim FolioNumber As String

For Each sItem As ListViewItem In lvList.SelectedItems
FolioNumber = sItem.Text
Next

With frmCheckIn
.State = modGlobal.FormState.adStatePopupMode
.FolioNumber = FolioNumber ' < = Variable "FolioNumber" is
used before it has been assigned a value. A null reference exception
coult result at runtime.

.ShowDialog()

Call FillList()
End With

frmCheckIn = Nothing

However, the FolioNumber variable has a comment from the IDE of VB.NET
as commented above.

Anyone know what is the better way of getting a value from selected
item in the listview?
 
J

James Hahn

What should the behaviour be if the For Each returns nothing (there are no
items selected)?

If it should use a default value then your should have:
Dim FolioNumber As String = "default string"

If the assignment should not happen then you need:
if not FolioNumber is nothing then _
.FolioNumber = FolioNumber

or put the whole thing in a test for lvList.SelectedItems > 0.
 
C

Coderz

Oh yes thanks for reminding me. But I think it is not necessary since
I am using a double click event of listview control.
 
J

James Hahn

That 'fix' has nothing to do with your problem, and has actually changed
your code so you are now returning the first selected item instead of the
last. You also haven't dealt with the problem of there being no item
selected.

The compiler warning is advising you that it is possible to reach the
assignment statement with FolioNumber set to nothing, a condition that will
cause a run-time error. You should re-structure the code to ensure this
won't happen, and then the compiler warning will go away.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top