DropDownList - FindByText

zubie

Centurion
Joined
Jul 1, 2003
Messages
103
Location
Ireland
Hey All

I have a dropdownlist where I'm trying to use the .FindByText property.

I check the .FindByText first and it is not returning a null.

When I use the .Selected = True at the end I recieve a System.NullReferenceException - Object reference not set to an instance of an object ...

Anyone know why this is?

cheers
ZuBiE
 
There is no "selected" property in a drop down list (I double checked to make sure). Are you refering to the "selected" property "SelectedItem" property?

When you select an item in a drop down list, it holds a reference to the selected item with the lowest index in the .SelectedItem property. If no items in the list are selected then the selectedItem property will be a null reference. You need to inspect the selecteditem reference before using it to ensure that it is acutally pointing to an item in the drop down list (in other words that you actually have an item in the drop down list selected). You do this as follows

If(Not ddlMyControl.SelectedItem Is Nothing)Then
'code here to work with the selected item...

End if

Keep in mind that if the selecteditem returns a listitem that logically that listitem's selected property will also return true.

If you are working with multiple selected items you need to get to them another way. Here is a snippet on how to do it.

Dim li as ListItem
For Each li in ddlMyList.Items
If(li.Selected)Then
'code here to work with the selected item...
End If
Next li

Hope that helps!
 
Hi

Thats roughly how I got it sorted.
My problem was that the search text has to be exactly like the text in the DDL.

So I used the following

Dim li as ListItem
li = DropDownList.Items.FindByText(strSearch)
if not IsNothing(li) then
DropDownList.Items.FindByText(strSearch).Selected = True
end if

this selects the item in the DDL.

cheers
ZuBiE
 
jspencer said:
Thanks for the code zubie. That's a tough one finding the selected property if you don't know where to look.

Your telling me ... did my nut in for a while I can tell you :D

later
ZuBiE
 
Back
Top