Thursday, March 29, 2012

List Box selected item count

I am trying to get the count in a list box for the items that are selcted.

I get Object reference not set to an instance of an object error


Dim iCnt as Integer
iCnt = myListBox.SelectedItem.Attributes.Count()

Now, this line of code works if one or more items are selected, but I need it to = 0 if none are selected.

And, if one or more is selected, it's always a 0 count.

Suggestions?

Thanks all,

ZathAs the listbox does not maintain a collection of selected items, you'll have to loop through the items collection, checking each listitem's selection property, and increment a counter for each listitem that is selected. The code you use simply counts the number of html attributes to be rendered for a selected listitem.


Dim iCnt As Integer=0
Dim li As ListItem
For Each li in myListBox.Items
If li.Selected Then iCnt += 1
Next

Check for a null reference first.
Dim intCnt As Integer = 0

If Not myListBox.SelectedItem Is Nothing Then
intCnt = myListBox.SelectedItem.Attributes.Count()
End If

You may want to verify that you are checking the right number though and refer to the above post. You are checking the HTML attributes of the selected <option> tag.
Thanks all. Now i am having trouble showing the actual item in the list....

I use myListBox.SelectedItem.Text and all I get is SELECT in the label to view it.

I need the name in the box.... I have tried every variation with no luck.

Suggetions?

Thanks again,

Zath
Nevermind, found my idiot error..... DOH

0 comments:

Post a Comment