vb.net string array null reference error - vb.net

i am creating an array in vb.net:
Dim BoldRows() as String
im adding values to the array here:
Dim detail_table_row as Integer = 1
While reader.read
detail_table_row = detail_table_row + 1
BoldRows(detail_table_row) = detail_table_row
End While
this is inside a loop and detail_table_row is a different number everytime it loops
then outside of my loop i have:
For Each row As Integer In BoldRows
oDoc_detail_table.Range.Rows(row).Range.Font.Bold = True
Next
but i am being told:
Variable 'BoldRows' is used before it has been assigned a value.

Because of
the problem is, i don't know how many elements the array is going to hold
Use List(Of T), From MSDN
Lists are exactly a type of collection which you can use when you don't know a number of items you will put in there.
Then your code will look like
'Integer because you assign Integer value in the List
Dim BoldRows As New List(Of Integer)()
Dim detail_table_row as Integer = 1
While reader.read
detail_table_row = detail_table_row + 1
BoldRows.Add(detail_table_row)
End While
For Each row As Integer In BoldRows
oDoc_detail_table.Range.Rows(row).Range.Font.Bold = True
Next
Arrays are still good in the cases where you know a number of the items.

try this :
Dim detail_table_row as Integer = 0
While reader.read
**ReDim preserve BoldRows(detail_table_row)**
BoldRows(detail_table_row) = detail_table_row
detail_table_row = detail_table_row + 1
End While

Related

vb- How to assign a different tag property to different array words?

This is my code for inserting from textfile to array to labels, but I want to be able to assign a tag property onto some of the words or perhaps use the 'Answer' which is located a line below on my text file??
IndexNo = 0
Dim FileTerm As String = "D:\soccer.txt"
Dim FileNum As Integer = FreeFile()
FileOpen(FileNum, FileTerm, OpenMode.Input)
Do
Term(IndexNo) = LineInput(FileNum)
Answer(IndexNo) = LineInput(FileNum)
IndexNo = IndexNo + 1
Loop Until EOF(FileNum)
FileClose(FileNum)
Dim Obj As Object, Count As Integer = 0
For Each Obj In Me.Controls
If TypeOf Obj Is Label Then
MyLabels(Count) = Obj
Count = Count + 1
End If
Next
Dim Random1, Random2 As Integer
Dim TempTerm, TempAnswer As Object
For Count = 0 To 15
Randomize()
Random1 = Val(Int(16 * Rnd()))
Random2 = Val(Int(16 * Rnd()))
TempTerm = Term(Random1)
Term(Random1) = Term(Random2)
Term(Random2) = TempTerm
TempAnswer = Answer(Random1)
Answer(Random1) = Answer(Random2)
Answer(Random2) = TempAnswer
Count = Count + 1
Next
For Count = 0 To 15
MyLabels(Count).Text = Term(Count)
Next
If anyone has any ideas, the help is appreciated. Thanks
Even though your question is not very clear. From what I get, you want to have some way to keep your Labels and the corresponding Term and Answers in sync.
There are many ways to do this, but I would prefer to do it as below... the perfect VB.NET way as opposed to using any legacy VB6 techniques.
First declare a class that would keep our Term and Answers in one object. This is the equivalent of Type in VB6.
Public Class TermAnswer
Public Term As String
Public Answer As String
' you may add more fields/properties here if you wish to...
End Class
Now it is easy to code our solution.
' declare a Dictionary object with Label as key and the corresponding Term and Answers as values.
Dim TermAnswers As New Dictionary(Of Label, TermAnswer)
' this is a temporary List to hold our Term and Answers read from file until we randomize them.
Dim tempTermAnswers As New List(Of TermAnswer)
' Our Labels array... yes it is this easy :)
Dim myLabels() As Label = Me.Controls.OfType(Of Label)().ToArray
' read our file into the tempTermAnswers List
Dim FileTerm As String = "D:\soccer.txt"
Using reader As New IO.StreamReader(FileTerm)
While Not reader.EndOfStream
Dim ta As New TermAnswer
ta.Term = reader.ReadLine
ta.Answer = reader.ReadLine
tempTermAnswers.Add(ta)
End While
reader.Close()
End Using
' pick Term Answers from our tempTermAnswers List randomly and add them to our TermAnswers Dictionary
' we also set our Label text here, though you can loop separately too
Dim randomNumbers As New Random
Dim tempTerm As TermAnswer, randomNumber As Integer
For Each label In myLabels
randomNumber = randomNumbers.Next(0, tempTermAnswers.Count)
tempTerm = tempTermAnswers(randomNumber)
TermAnswers.Add(label, tempTerm)
tempTermAnswers.Remove(tempTerm)
label.Text = tempTerm.Term
Next
' now you have your term answers in a Dictionary, indexed by Label.
' you can get any of them by providing a Label on your form as key and get the corresponding Term and Answer as value.
' e.g. let us list the Label Name, Term and Answer in our debug window...
For Each label In myLabels
Debug.WriteLine(label.Name & " ... " & TermAnswers(label).Term & " ... " & TermAnswers(label).Answer)
Next

VB.NET Error Populating 2d Array with database field

i have a query that contains field "kode_brg"
i want to fill them into array2d, i'm using mysqldatareader to fill the field into array2d, but it seems that the datareader only read once inside the while looping
for more specific, i've added the ss of myproblem belom
i'm pretty sure that i've made a mistake in using the nested for inside the while loop
could somebody help me fix this problem
thanks before
regards, me
EDITED: ADDED A CODE TO A QUESTIONS
'FILL X
Dim nil_x As String = "SELECT max( kode_faktur ) FROM detail"
Dim x As Int32
Dim CMD_X = New MySqlCommand(nil_x, conn.konek)
x = Convert.ToInt32(CMD_X.ExecuteScalar())
'FILL Y
Dim nil_y As String = "select max(x.jumlah) from (select count(*) as jumlah from detail group by kode_faktur)x"
Dim y As Int32
CMD_Y = New MySqlCommand(nil_y, conn.konek)
y = Convert.ToInt32(CMD_Y.ExecuteScalar())
'LOOPING ARRAY TRANS
Dim msql As String = "select kode_brg from detail group by kode_faktur"
Dim i, j As Integer
Dim arayT(,) As String
CMD = New MySqlCommand(msql, conn.konek)
'Try
Dim hasil As MySqlDataReader
hasil = CMD.ExecuteReader()
While hasil.Read()
For i = 0 To x
ReDim Preserve arayT(x, y)
For j = 0 To y
arayT(i, j) = hasil("kode_brg")
'Continue For
Next j
j += 1
'Continue For
Next i
i += 1
Exit While
End While
conn.konek.Close()
dgv2.RowHeadersWidthSizeMode = DataGridViewRowHeadersWidthSizeMode.EnableResizing
dgv2.RowHeadersWidthSizeMode = DataGridViewRowHeadersWidthSizeMode.AutoSizeToAllHeaders
dgv2.RowHeadersVisible = False
With Me.dgv2
.DataSource = New Mommo.Data.ArrayDataView(arayT)
.SelectionMode = DataGridViewSelectionMode.FullRowSelect
.AllowUserToAddRows = False
.RowHeadersVisible = True
End With
one big note from me
DON'T SUGGEST ME TO USE ARRAYLIST/LIST OF/LINQ/DATASET/DATATABLE
because what i really want to do is filling the 2d array with database field, comparing it with another 1d array, then create a new 2d array from both of them, finally i want to display the newly 2d array into the grid.. that's why i chose 2d array instead using dataset to fill my grid
i don't know how to compare list(of) or arraylist with 1d array, that's why i'm using 2d array (basic)
thanks you before :)
the desired output
Assuming you managed to get array size exactly the same as number of data returned from query, you can try to change the loop to following :
ReDim Preserve arayT(x, y)
For i = 0 To (x-1)
For j = 0 To (y-1)
hasil.Read()
arayT(i, j) = hasil("kode_brg")
'Continue For
Next j
'Continue For
Next i
I have no idea of what you're trying to accomplish, but this is how you should do it:
Dim list As New List(Of String(,))
While hasil.Read()
Dim item(,) As String = New String((x - 1), (y - 1)) {}
Dim value As String = hasil("kode_brg")
For i As Integer = 0 To (x - 1)
For j As Integer = 0 To (y - 1)
item(i, j) = value
Next
Next
list.Add(item)
End While

For loop make new variables for you - VB.Net

I'm trying to make a for loop for will make a new variable for me, every step. I want something like this. What ever step I am on, say, x = 2, it Dims newVar2, if x = 3: Dim newVar3
Is there any way to do that? I was hoping something like, Dim newVar & x would work, but of course now.
I was trying to do it as an array, but I'm not sure how to do that, or ReDimming, so examples would be great!
To create a collection of variable values inside a for loop, you should use a List(Of t) object or something similar (For Example Dictionary).
To do this with a List(Of t) you can do the following :
Dim varList As New List(Of Integer)
For i As Integer = 0 To 10
varList.add(i)
Next
Or if you want to do it with the variable names you mentioned, try :
Dim varList As New List(Of String)
For i As Integer = 0 To 10
varList.add("newVar" & i)
Next
To retrieve the value from a List use the following : Dim result As String = varList(0)
Alternatively you can use a Dictionary object to store Key/Value pairs :
Dim varList As New Dictionary(Of String, Integer)
For i As Integer = 0 To 10
Dim k As Integer = 0
varList.add("newVar" & i, k)
Next
Becareful though as a Dictionary object can only contain unique Keys. To return the value find it as : Dim result As Integer = varList("newVar0")
basic array:
Dim Arr(1000) As Integer
For i As Integer = 0 To 999
Arr(i) = YYYYY
Next
trick for dynamic size:
Dim max As Integer = XXXXXX
Dim Arr(1000) As Integer
For i As Integer = 0 To max
'if too small, Increasing array without loss old data
If Arr.Length = i Then
ReDim Preserve Arr(Arr.Length + 1000)
End If
Arr(i) = YYYYY
Next
or, use list:
Dim max As Integer = XXXXXX
Dim list As New List(Of Integer)
For i As Integer = 0 To max
list.Add(YYYYY)
Next
The other answers are technically correct, but you probably don't need the iteration loops. You can probably do this in a single line of code:
Dim varList As Dictionary(Of String, String) = Enumerable.Range(0, 10).ToDictionary(Function(k) "newVar" & k, Function(v) "Some value for newVar" & v)
Dim myInts As New List(Of Int)
For i = 0 To 10
myInts.Add(i)
Next

How to get each value in an array and show it in a listbox

Hi I am new to VB and I have problems with using array. My code is like that.
This is class FindFactorsObject.vb
Public Sub FindFactors()
count = 0
temp = Convert.ToInt32(Math.Sqrt(_x))
For i As Integer = 1 To temp
If _x Mod i = 0 Then
ReDim array(count)
array(count) = i
count += 1
End If
Next
So I created an array and stored the results. Now I want to display each value in my array in Form.vb and if it is possible can somebody teach me how to make delay for each of the displayed value. Thanks very much
Always declare your variables, if possible to their exact types, you think they will take care of. When you say 'Now I want to display each value in my array in Form.vb' I understood literally: in the Form so, we will print them on your form
Public Sub FindFactors(_x As Integer)
Dim temp As Integer = Convert.ToInt32(Math.Sqrt(_x))
Dim l As New List(Of Integer)
For i As Integer = 1 To temp
If _x Mod i = 0 Then
l.add(i)
End If
Next
Dim pf As New PointF(20, 20)
For Each i As Integer In l
creategraphics.drawstring(i.ToString, New font(font.fontFamily, 24), brushes.cadetblue, pf)
pf = New PointF(pf.X, pf.Y + 30)
Next
End Sub

Need help with VB.NET List Logic

Hey guys, so I am creating a List(Of String), always of size 9.
This list contains True/False values. I need to go through this list and find the 3 values that are True (will never be more than 3, but could be less) and then set 3 string values in my code to the 3 index's of those values + 1.
Here is my current code:
Private Sub SetDenialReasons(ByVal LoanData As DataRow)
Dim reasons As New List(Of String)
With reasons
.Add(LoanData.Item("IsDenialReasonDTI").ToString)
.Add(LoanData.Item("IsDenialReasonEmploymentHistory").ToString)
.Add(LoanData.Item("IsDenialReasonCreditHistory").ToString)
.Add(LoanData.Item("IsDenialReasonCollateral").ToString)
.Add(LoanData.Item("IsDenialReasonCash").ToString)
.Add(LoanData.Item("IsDenialReasonInverifiableInfo").ToString)
.Add(LoanData.Item("IsDenialReasonIncomplete").ToString)
.Add(LoanData.Item("IsDenialReasonMortgageInsuranceDenied").ToString)
.Add(LoanData.Item("IsDenialReasonOther").ToString)
End With
Dim count As Integer = 0
For Each item As String In reasons
If item = "True" Then
count += 1
End If
Next
If count = 1 Then
DenialReason1 = (reasons.IndexOf("True") + 1).ToString
ElseIf count = 2 Then
DenialReason1 = (reasons.IndexOf("True") + 1).ToString
DenialReason2 = (reasons.LastIndexOf("True") + 1).ToString
ElseIf count >= 3 Then
Dim tempIndex As Integer = reasons.IndexOf("True")
DenialReason1 = (reasons.IndexOf("True") + 1).ToString
DenialReason2 = (reasons.IndexOf("True", tempIndex, reasons.Count - 1) + 1).ToString
DenialReason3 = (reasons.LastIndexOf("True") + 1).ToString
End If
End Sub
I had 3 True's next to each other in the array and the code failed with an exception saying count must be positive or something.
Now if there are less than 3 True's, it should set the remaining DenialReason's that haven't been set yet as blank (however they are set as blank in the constructor already to account for this).
Any ideas?
Perhaps you could modify your For Each code to handle the assignment of the DenialReasons. This still feels like a hack, but I think it may be cleaner that what you have. If you use this code, you don't need the code that begins with If count = 1...:
Dim count As Integer = 0
Dim index As Integer = 1
For Each item As String In reasons
If item = "True" Then
count += 1
Select Case count
Case 1
DenialReason1 = index.ToString()
Case 2
DenialReason2 = index.ToString()
Case 3
DenialReason3 = index.ToString()
End Select
End If
index += 1
Next
The index variable above assumes a 1-based index. I think this is cleaner than using IndexOf().
I think a better solution might be to have a list of DenialReasons and add to that list as items are true:
Dim count As Integer = 0
Dim index As Integer = 1
Dim denialReasons As New List(Of String)()
For Each item As String In reasons
If item = "True" Then
denialReasons.Add(index)
End If
index += 1
Next
Then you can simply iterate through your list of denialReasons. This is flexible so that if, for whatever reason, you have more than three DenialReasons, you don't have to add another hard-coded variable.