How to assign a value to an array from a combobox - vb.net

The code I have is:
Dim Dbase() As String = Nothing
Dbase(0) = Db_ComboBox.Text
I have declared Dbase as array and assigned Nothing, Db_ComboBox is a combobox.
For that assignment statement, I'm getting the following error: "Reference 'Dbase' has a value of 'Nothing'"
What is the reason for this error, and how can I take the value from the combobox and save it in the array?

You need to change this:
Dim Dbase() As String = Nothing
to this (declare an array of 1 element):
Dim Dbase(0) As String
And then this line will work:
Dbase(0) = Db_ComboBox.Text
If you need to change your array size you can use Redim or Redim preserve, as required.
If you anticipate contents of Dbase to change often, I am all with #Joel's suggestion about switching to List(Of String) instead of handling array sizes manually.

Let's look at your code:
Dim Dbase() As String = Nothing
Dbase(0) = Db_ComboBox.Text
Especially the first line. That first line creates a variable that can refer to an array, but the = Nothing portion explicitly tells it, "Do not create a real array here yet". You have, effectively, a pointer that doesn't point to anything.
I get here that what you really need is a List collection that you can append to over time:
Dim Dbase As New List(Of String)()
Dbase.Add(Db_ComboBox.Text)

Dbase() IS NOTHING. Look at this example:
cargoWeights = New Double(10) {}
atmospherePressures = New Short(2, 2, 4, 10) {}
inquiriesByYearMonthDay = New Byte(20)()() {}
That's how you declare arrays.
More examples: http://msdn.microsoft.com/en-us/library/vstudio/wak0wfyt.aspx

Related

Getting the value of string from a jagged array when using option strict

I've just started using option strict (based on advice from another question) and I'm stuck!
I have an array which contains more arrays. The second array contains strings. I can't work out how to get the values of the strings out of the second array.
dim sb as new stringbuilder
public sub foobar({{"abcd", "efg"},{"hjik", "lmnop"}}
for each arr in master
sb.AppendLine(arr(0))
next
end sub
But I get a late binding error. I understand why I'm getting the error but how do I get around it?
Assuming master looks similar to what you're passing in to foobar, then arr(0) get's you to element 0 of the first dimension of the array, you'd need to iterate over that array if you want to append all elements from each second level array.
With Option Strict you will also need to declare the type of each variable, so it is going to get pretty "wordy":
Dim aryOfArrays()() As String = _
New String()() {New String() {"1a", "1b"}, New String() {"2a", "2b"}}
For Each aryOfStrings As String() In aryOfArrays
For Each strElement As String In aryOfStrings
sb.AppendLine(strElement)
Next
Next
https://msdn.microsoft.com/en-us/library/kfky451c(v=vs.90).aspx
You should define variables in vb.net in the begging of the function.
Move the "dim str" to the beginning of function
more details

NullReferenceException was unhandled in small loop

Hello I recieve a "nullreferenceexception was unhandled" error when I try to run this code:
For i As Integer = 1 To aantaltags
csvopc(i) = csvtagssplit(17 * i)
csvsql(i) = csvtagssplit(17 * i + 15)
Next
Background:
I read a csv file that I clean up and split into csvtagssplit()
csvopc and csvsql are both declared as string() at the top of the program.
anything dumb I did and I'm not noticing?
replicate it if you want to:
code:
http://pastebin.com/JDPa6FSB
csv:
http://pastebin.com/2e66i9EB
Your problem is in the intial part of your code where you declare the two variables cvsopc and cvssql,
As from your comment you write
Dim csvopc As String()
Dim csvsql As String()
But this only declares the two variables without any dimension.
So when you try to reach csvopc(i) you are effectively referencing a index that doesn't exist
Why use arrays when you don't know the exact size of your elements?.
You can easily switch to a List(Of String) where you can dinamically add elements
Dim csvopc As List(Of String) = new List(Of String)
Dim csvsql As List(Of String) = new List(Of String)
and then in your loop
For i As Integer = 0 To aantaltags - 1
csvopc.Add(csvtagssplit(17 * i))
csvsql.Add(csvtagssplit(17 * i + 15))
Next
A List(Of String) could also be referenced by Index as in
Dim aValue = csvopc(0)
You should step through your code with a debugger in order to inspect the data as the code runs. You could put a breakpoint at a place where everything should be initialized but before the exception happens and then see what the values are.
Which iteration of the loop fails, and what line specifically fails? Put a breakpoint on that line and see what all the values are immediately before the line executes. If this debugging doesn't reveal the error to you, update your post with the data you find during debugging and maybe we can get somewhere.

IndexOf a ComboBox just will not work for me

VB2010. I am trying to populate a ComboBox with the contents of an Enumeration of units. I have managed to do this with a Dictionary. Something like
Dim dUnits As New Dictionary(Of String, Integer)
Dim da As String
For Each enumValue As eUnits In System.Enum.GetValues(GetType(eUnits))
da = ConvertEnumToCommonName 'gets unique name for an enumeration
dUnits.Add(da, enumValue)
Next
cbo.DisplayMember = "Key" 'display the the common name
cbo.ValueMember = "Value" 'use the enumeration as the value
cbo.DataSource = New BindingSource(dUnits, Nothing)
When I load up my form that works well. Now the user can choose to select a default unit to display. So then I try
Dim defUnits As eUnits = eUnits.Feet
Dim idx As Integer = cbo.Items.IndexOf(defUnits) 'doesnt work, returns a -1
cbo.SelectedIndex = idx
I have been doing some research for some time and am fairly sure that this has to do with the ComboBox storing Values as a string and in reality I'm searching for an enumeration which is an integer. Don't know if I have that right or not. Anyway, I just cant seem to get the default item selected. Is there another approach I can try?
First of all you have a collection of integers and you're searching for the enum value. For that, try one of the following:
Store the enum value in the dictionary instead of a string:
Dim dUnits As New Dictionary(Of String, eUnits)
Keep the integers in the Dictionary but use the integer value of the enum when searching the ComboBox:
Dim idx As Integer = cbo.Items.IndexOf(CInt(defUnits))
But this is not going to work yet. You are data-bound to a Dictionary, which means the items in cbo.Items are not of the enum type, but of the type of the elements in the Dictionary (KeyValuePair(Of String, eUnits) assuming #1 above).
The easiest solution is just to set the SelectedValue property of the combo box instead of the SelectedIndex. Assuming you used option #1 above, this would be:
cbo.SelectedValue = defUnits
If you used option #2 instead, you'll have to convert this to an integer first:
cbo.SelectedValue = CInt(defUnits)

Adding values to array

I am trying to run an event which will search through the different files in a given directory. The goal is to have it search for all files that begin with 'SP_', which are .sql files containing Stored Procedures. I would then like to add the full text of these Procedures to an array to be used later. This is causing an error when run, which I believe is because 'FullProcedureArray()', the string array I am trying to load does not have defined boundaries. When I declare it as 'FullProcedureArray(7)', or with some other value, it appears to run fine. But I don't want to have to hard-code a boundary for 'FullProcedureArray'; I would rather let it be defined by whatever the number of files in the folder is.
My question: Is there a way to declare 'FullProcedureArray' without having to give it an absolute value? I may just be missing something painfully obvious, but I haven't worked with this type of array much in the past. Thanks in advance for your help.
Dim AppDataLocation As String = "C:\Files\TestFiles\"
Dim ProcedureArray As String()
Dim ProcedureText As String
Dim FullProcedureArray() As String
Dim sourceDirectoryInfo As New System.IO.DirectoryInfo(AppDataLocation)
Dim fileSystemInfo As System.IO.FileSystemInfo
Dim i As Integer = 0
For Each fileSystemInfo In sourceDirectoryInfo.GetFileSystemInfos
If (fileSystemInfo.Name.Contains("SP_")) Then
ProcedureArray = System.IO.File.ReadAllLines(AppDataLocation & fileSystemInfo.Name)
ProcedureText = Join(ProcedureArray, "")
FullProcedureArray.SetValue(ProcedureText, i)
i = (i + 1)
End If
Next
An array by definition has a fixed upper bound. If you don't want a fixed upper bound, don't use an array. Use, for example, a List(Of String) instead:
Dim AppDataLocation As String = "C:\Files\TestFiles\"
Dim ProcedureList As New List(Of String)
Dim sourceDirectoryInfo As New System.IO.DirectoryInfo(AppDataLocation)
For Each fileSystemInfo As System.IO.FileSystemInfo In sourceDirectoryInfo.GetFileSystemInfos
If (fileSystemInfo.Name.Contains("SP_")) Then
Dim ProcedureText As String = _
System.IO.File.ReadAllText(AppDataLocation & fileSystemInfo.Name)
ProcedureList.Add(ProcedureText)
End If
Next
If, for some reason, you still need the result as an array afterwards, simply convert the list to an array:
Dim myArray() As String = ProcedureList.ToArray()
If you don't want to give a size to your array or want to change at runtime, you can use "Redim Preserve"
http://msdn.microsoft.com/en-us/library/w8k3cys2%28v=vs.71%29.aspx

Why won't this list of struct allow me to assign values to the field?

Public Structure testStruct
Dim blah as integer
Dim foo as string
Dim bar as double
End Structure
'in another file ....
Public Function blahFooBar() as Boolean
Dim tStrList as List (Of testStruct) = new List (Of testStruct)
For i as integer = 0 To 10
tStrList.Add(new testStruct)
tStrList.Item(i).blah = 1
tStrList.Item(i).foo = "Why won't I work?"
tStrList.Item(i).bar = 100.100
'last 3 lines give me error below
Next
return True
End Function
The error I get is: Expression is a value and therefore cannot be the target of an assignment.
Why?
I second the opinion to use a class rather than a struct.
The reason you are having difficulty is that your struct is a value type. When you access the instance of the value type in the list, you get a copy of the value. You are then attempting to change the value of the copy, which results in the error. If you had used a class, then your code would have worked as written.
try the following in your For loop:
Dim tmp As New testStruct()
tmp.blah = 1
tmp.foo = "Why won't I work?"
tmp.bar = 100.100
tStrList.Add(tmp)
Looking into this I think it has something to do with the way .NET copies the struct when you access it via the List(of t).
More information is available here.
Try creating the object first as
Dim X = New testStruct
and setting the properties on THAT as in
testStruct.blah = "fiddlesticks"
BEFORE adding it to the list.