How can i check if a string collection is empty? I triedBut it saidVB.NET Code:
My.Settings.IPBank.Count = 0Quote:
Object reference not set to an instance of an object.
Printable View
How can i check if a string collection is empty? I triedBut it saidVB.NET Code:
My.Settings.IPBank.Count = 0Quote:
Object reference not set to an instance of an object.
That means that the object has not been created, or instantiated, yet.
You'd need to create a new one if it is Nothing:
After doing that, you can check if its empty or not.Code:If My.Settings.IPBank Is Nothing Then
My.Settings.IPBank = New WhateverTypeIPBankIs()
End If
That error shouldn't rule out the attempt, as it generally means that something was not instantiated. If you put a breakpoint on that line and highlight the:
My.Settings.IPBank portion, then use Shift+F9 to look at the value, you will probably find that it is Nothing. That test, alone, may be sufficient. If that portion is Nothing, then you might try something like this:
If My.Settings.IPBank Is Not Nothing AndAlso My.Settings.IPBank.Count>0 Then
The second half of the condition will only evaluate if the first half evaluates to True, so you won't get the error, and will have a pretty robust way of checking whether the collection even exists, and whether it has more than zero items.
That answer makes a few assumptions about how you have things set up, though.
but there is alredy a stringcollection in the my.settings
I would say that there isn't, even though you think it should be there. The test I suggested will tell you that.
Just because you created a StringCollection setting in the Settings list does not mean it holds a StringCollection object yet. You still need to create a New StringCollection:
This is exactly the same as when you are using a List(Of String) in normal code (which is a similar collection):Code:My.Settings.yourSetting = New StringCollection()
Now, list is Nothing and list.Count will not work. You first need to do:Code:Dim list As List(Of String)
As you may see, it's exactly the same thing: you need to create a new instance of an object before you can use it.Code:Dim list As List(Of String)
list = New List(Of String)
When you add a StringCollection to your Settings it essentially declares a variable but it does not create an object, as NickThissen suggests. If you don't want to add code to create the StringCollection object you can force it to be created in the Settings. Select the Value field in the Settings editor and then click the browse button to open the string editor. Add a dummy value and click OK. You'll see that there's now some XML code in the Value field. It's that XML code that creates and optionally populates the StringCollection. You can now open the string editor again and remove your dummy value. When you click OK you'll see that the Value property still contains some XML but examination will reveal that it contains no items.